# simple for loop

• Sep 29th 2011, 09:08 AM
noob mathematician
simple for loop
Suppose I have a matrix, $\begin{bmatrix}1 & 3\\ 2 & 4\end{bmatrix}$, "in r, we have a=matrix(1:4,nrow=2)"

I define another vector (1,2,3), "in r, we have b=c(1,2,3)"

I have set up a for loop,

"new=NULL
for (i in 1:length(b))new=c(new,a+b[i])"

I obtain new= 2 3 4 5 3 4 5 6 4 5 6 7, this return me with a vector.. but I want a matrix

So I convert by coding,

"for (i in 1:3) {c[i]=matrix(new[(1+4*(i-1)): (4+4*(i-1))],nrow=2)}"

in hope that my c[1] equals $\begin{bmatrix}2 & 4\\ 3 & 5\end{bmatrix}$, c[2] equals $\begin{bmatrix}3 & 5\\ 4 & 6\end{bmatrix}$ and c[3] equals $\begin{bmatrix}4 & 6\\ 5 & 7\end{bmatrix}$,

However I received an error, what's wrong with the above code?
(Note the code is working fine if I use for (i in 1:3) {print(matrix(new[(1+4*(i-1)): (4+4*(i-1))],nrow=2))} to print the result, but I can't seem to allocate the matrix to c[i] :()