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 日

0 投票

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 ExchangeMathematics についてさらに検索

タグ

質問済み:

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