FOR loop calculating next values using the previous values
4 次查看(过去 30 天)
显示 更早的评论
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!
2 个评论
采纳的回答
Aquatris
2019-1-7
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
2 个评论
Aquatris
2019-1-7
I don't think so since the value of the last station requires information for the 258th values, which do not exist. You might want to check the origin of the equations and see how this is handled.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!