How to convert a dot product inside a MATLAB for loop into RStudio?

Hello. 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 425 matrix. Here is the screenshot of the first few rows of yhb created from the for loop.

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)])
}

As you can see that for me to get the dot product I use sum(vector_a * vector_b). And, from the MATLAB code which reverses the order of the elements in hat, I use the function rev(hat). I am not confident whether this is the right way, particularly, whether I can use the function rev to index/access the columns of 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 tried to manually verify where I am getting it wrong by running these individual set of codes:

hat2 <- hat[2,]
for (i in 1:(s-m+k)) {
krf <- krf[7,1:i]
}
hat3 <- as.matrix(t(rev(hat2))

At this point, hat3 exactly replicates the hat(2,i:-1:1) inside the MATLAB for loop, so far so good. But then when I issue this command:
yhb <- as.matrix(sum(krf*hat3))

I am able to get the correct dimension of yhb but does not replicate the one produced by the MATLAB for loop above. I am stuck.

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

Let me just explain further my difficulty. I 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 RStudio where the index is from 1:(s-m+k)?

Because of this, the previous for loop I did in RStudio which I showed in my earlier question is not correct including the manual dot product at the very end of my previous question. Again, many thanks for any help you can provide.

sorry, the matrix hat has dimensions 4 x 449 not 4 x 445 as previously noted in my question.

This topic was automatically closed 21 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.