# A Hack to Create Matrices in R, Matlab style

The Matlab syntax for creating matrices is pretty and convenient. Here is a 2x3 matrix in Matlab syntax where , marks a new column and ; marks a new row:

Here is how to create the corresponding matrix in R:

Functional but not as pretty, plus the default is to specify the values column wise. A better solution is to use rbind:

Lately I’ve been reading up on the metaprogramming capabilities of R in Hadley Wickham’s great Advanced R programming (while it is freely available online, you can already pre-order the IRL version here). Using metaprogramming we can hack together a function that allow us to create matrices in a similar way as in Matlab. I’ll first show some examples of how the function works and after that I’ll show you the code. The function is called qm as in “quick matrix” where , is used to separate columns and | is used to separate rows:

Pretty cool, right? :)

Here is finally the full qm function. The trick is roughly to grab the arguments to qm as a list, split every argument with a | into two, and finally form the rows of the matrix by evaluating and concatenating the arguments between each |. (qm is not extensively tested so use it at your own risk and please tell me if you find any way to improve the code!)

While I’m not sure that qm is really a super useful function, I still think it is a nice example of what you can hack together using the metaprogramming facilities of R.