# How to translate a for loop in MATLAB to RStudio?

Hello, I want to convert this MATLAB for loop into RStudio:

``````p=24;
t=455;

for i=1:p-1
Y=[Y; y(:,p-i:t-i)];
end;
``````

The Y matrix has a dimension 4x432 and y matrix is 4x455.

The code I tried in RStudio is:

``````for (i in 1:p-1) {
Y<- rbind(Y, y[,p-i:t-i])
}
``````

However, I am getting an error which says: Error in y[, p - i:t - i] : subscript out of bounds.

Based on the output in MATLAB, the Y matrix must become a 96 by 432 matrix after running the above for loop.
Thank you very much.

`(p-i):(t-i)`

It is still giving me the same error.
I also get the same error when I put a parentheses on (i in 1:(p-1))

That ought to work . Just as a check, have you done `str(y)` or something to be sure `y` is in fact the right size?

It now works when I run this code in RStudio:

for (i in 1:(p-1)) {
Y<- rbind(Y, yy[,(p-i):(t-i)])
}

With this code, I am able to get the same 96 by 432 Y matrix in RStudio.
The matrix y in the above MATLAB code should be yy in my RStudio environment. I was indexing/accessing the wrong matrix in my previous RStudio code. My sincere apologies for the earlier mistake. For my own learning and understanding, would you please explain why putting parentheses in the for loop of the RStudio code worked? Many thanks.

First thing, no apologies due. We all do this sort of thing all the time. Human brains see what they think is there instead of what's actually there much too often.

In Matlab, the minus sign is applied before the colon. In R, that isn't true. Hence the need for parentheses.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.