Error in storing the values from a loop to a matrix

I am getting error while storing values of loop .
iterations = 10;
t = zeros(2,iterations);
for i = 1:iterations
theta1 = t(1) + 3;
theta2 = t(2) + 5;
t(1) = theta1;
t(2) = theta2;
t(1,i) = theta1;
t(2,i) = theta2;
end
disp(t)
I should have got 3 and 5 in the first column. But i am getting 30 and 50

답변 (1개)

Walter Roberson
Walter Roberson 2017년 9월 10일
No, the result you got was what you programmed. Remember that linear indexing goes down columns. Your code is exactly equivalent to
iterations = 10;
t = zeros(2,iterations);
for i = 1:iterations
theta1 = t(1,1) + 3;
theta2 = t(2,1) + 5;
t(1,1) = theta1;
t(2,1) = theta2;
t(1,i) = theta1;
t(2,i) = theta2;
end
disp(t)
Notice that you keep writing new values into t(1,1) and t(2,1), continually adding 3 or 5 to them. The end result is going to be 3 * iterations or 5 * iterations.

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

태그

질문:

2017년 9월 10일

답변:

2017년 9월 10일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by