Error in storing the values from a loop to a matrix
2 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
回答 (1 件)
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!