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!