Home > Software design >  How to translate this MATLAB for loop in R?
How to translate this MATLAB for loop in R?

Time:07-21

I want to convert this MATLAB for loop into R:

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 R code I tried 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 96x432 matrix after running the above for loop.

I can get to the same result in R by running these quite long set of codes:

yyy1 <- as.matrix(yy[,23:454])
yyy2 <- as.matrix(yy[,22:453])
yyy3 <- as.matrix(yy[,21:452])
yyy4 <- as.matrix(yy[,20:451])
yyy5 <- as.matrix(yy[,19:450])
yyy6 <- as.matrix(yy[,18:449])
yyy7 <- as.matrix(yy[,17:448])
yyy8 <- as.matrix(yy[,16:447])
yyy9 <- as.matrix(yy[,15:446])
yyy10 <- as.matrix(yy[,14:445])
yyy11 <- as.matrix(yy[,13:444])
yyy12 <- as.matrix(yy[,12:443])
yyy13 <- as.matrix(yy[,11:442])
yyy14 <- as.matrix(yy[,10:441])
yyy15 <- as.matrix(yy[,9:440])
yyy16 <- as.matrix(yy[,8:439])
yyy17 <- as.matrix(yy[,7:438])
yyy18 <- as.matrix(yy[,6:437])
yyy19 <- as.matrix(yy[,5:436])
yyy20 <- as.matrix(yy[,4:435])
yyy21 <- as.matrix(yy[,3:434])
yyy22 <- as.matrix(yy[,2:433])
yyy23 <- as.matrix(yy[,1:432])
yyy <- rbind(yyy1, yyy2, yyy3, yyy4, yyy5, yyy6, yyy7, yyy8, yyy9, yyy10, yyy11, yyy12, yyy13, yyy14, yyy15, yyy16, yyy17, yyy18, yyy19, yyy20, yyy21, yyy22, yyy23)
Y <- rbind(Y, yyy)

I know that this is not the most efficient way of doing it, that is why I want to translate the above MATLAB for loop into R.

CodePudding user response:

Need ()

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

guess what, 1:4-1 is not 1, 2, 3

BTY, your question is wrong. y should be 4 x 455.

  • Related