Home > Software engineering >  How to translate a dot product in a MATLAB for loop to R?
How to translate a dot product in a MATLAB for loop to R?

Time:07-23

I have been trying for many hours now how to successfully translate this MATLAB dot product inside a for loop into RStudio. Here is the MATLAB code:

m = 24;
k = 24;
s = 449:
yhb= zeros(s-m k,1);
for i = 1:s-m k
     yhb(i,:)=dot(krf(7,1:i),hat(2,i:-1:1));
end

yhb is a 449 x 1 vector, krf is a 16 x 449 matrix, and hat is a 4 by 449 matrix. Here is the screenshot of the first few rows of yhb created from the for loop.

[screenshot of the first few rows of yhb created from the MATLAB for loop][1]

Here is the code that I first tried in RStudio:

m <- 24
k <- 24
s <- 449
yhb <- matrix(0,s-m k,1)

for (i in 1:(s-m k)) {
      yhb[i,] <- sum(krf[7,1:i]*hat[2,rev(hat)])
}

I am then getting an error message which is this:

Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'sum': only 0's may be mixed with negative subscripts

I then realized that the MATLAB for loop above essentially makes these calculations to obtain the elements of yhb:

yhb[1,1] = krf[1,1]*hat[1,1]

yhb[2,1] = krf[1,1]*hat[1,2] krf[1,2]*hat[1,1]

yhb[3,1] = krf[1,1]*hat[1,3] krf[1,2]*hat[1,2] krf[1,3]*hat[1,1]

so on and so forth.. How can I create a for loop such as this in R where the index is from 1:(s-m k)?

I am stuck. Appreciate any help you can provide, please. Thank you so much.

CodePudding user response:

The i:-1:1 in MATLAB becomes i:1 in R, so the for loop should be:

for (i in 1:449) yhb[i] <- sum(krf[7, 1:i]*hat[2, i:1])
  • Related