# R vs. Matlab – a small example

February 15, 2010
By

At the institute I’m working quite a lot of people prefer using Matlab and only a few of them know about R. Today one of my colleagues — who is also an eager user of Matlab — ran into the following problem:

• He had a vector $v$ in hand which consisted of $\frac{n(n+1)}{2}$ elements.
• He wanted to reshape this data into an n×n matrix $M$, where the element $M_{ij}$ is equal to $v_{k+j}I(j<=n-i+1)$ with $k=\frac{(2n-i+2)(i-1)}{2}$ and $I(j <= n-i+1)=1$ if the condition $j <= n-i+1$ is satisfied and $0$ otherwise. In other words, the first $(n-i+1)$th element of the $i$th row of $M$ is equal to the vector $(v_{k+1},v_{k+2},\ldots,v_{k+n-i+1})$ and the remaining elements are zero.

He struggled for long minutes of how he should design a loop for doing this task. Of course writing such a loop is not a highly difficult task, but why would we waste our time, if we can get the same result in a single line of R code?

For the sake of illustration, I’ve generated an input vector for the case of $n=99$ (the value of $n$ was 99 in my colleague’s problem as well):

v <- rep(99:1,times=99:1)

and used the one-liner

M <- t(matrix(unlist(tapply(v,rep(1:99,times=99:1),function(x) c(x,rep(0,99-length(x))))),nrow=99))

This is the kind of compactness I like pretty much in R. At the end I would like to emphasize that this post is not against Matlab, it just points out how the different logic of the R language can simplify problem solving in many situations. As a bonus let me share the visualization of the resulted matrix using the color2D.matplot function of the plotrix package:
 library(plotrix) color2D.matplot(M,c(0,1),c(1,0),c(0,0))