63 views (last 30 days)

Hi there,

I have a pre-defined matrix 257 x 3 matrix, say Xin = [X Y Z]. Based on that, I would like to calculate a new matrix Xout = [M N P], using the values from Xin, such that e.g.:

M1 = (X2-X1) * sin(Y1*Z1) * cos(Y2*Z2)

M2 = (X3-X2) * cos(Y2*Z2) * sin (Y3*Z3)

and so on until the last value of 257.

So far I used the FOR loop (1:size(Xin,1)) and tried to pull the values from Xin using (i) and (i-1), however it states that "Subscript indices must either be real positive integers or logicals" that obviously happens when i=1.

I tried to overcome this by pre-defining X1,Y1,Z1 from Xin such e.g., X1 = Xin (1,1) and then start the FOR loop from (2:size(Xin,1)) but then it gives an error that index exceeds matrix dimensions.

X1,Y1,Z1 cannot initially be set up as some random values, since they come from the real survey data.

Any help would be appreciated. Thank you in advance!

Aquatris
on 7 Jan 2019

Your for loop cannot go upto size(Xin,1). Imagine Xin has 10 elements. For calculation of M10, you would need to access Xin(11), which does not exist. This is why you were getting index exceed matrix dimensions error.

For the "Subscript indices must either be real positive integers or logicals" error, I think you did not use "i" as your loop counter variable. "i" is by default equal to sqrt(-1), an imaginary number, in Matlab.

From what I understand you are trying to do;

X = Xin(:,1); Y = Xin(:,2); Z = Xin(:,3);

for i = 1:(size(Xin,1)-1)

% assuming the 'M1=(X2-X1)*sin(Y1*Z1)*cos(Y2*Z2)' is the correct formula

M(i) = (X(i+1)-X(i)) * sin(Y(i)*Z(i)) * cos(Y(i+1)*Z(i+1));

end

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/438675-for-loop-calculating-next-values-using-the-previous-values#comment_657878

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/438675-for-loop-calculating-next-values-using-the-previous-values#comment_657878

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/438675-for-loop-calculating-next-values-using-the-previous-values#comment_657904

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/438675-for-loop-calculating-next-values-using-the-previous-values#comment_657904

Sign in to comment.