Error in storing the values from a loop to a matrix

1 vue (au cours des 30 derniers jours)
HIRAKJYOTI BASUMATARY
HIRAKJYOTI BASUMATARY le 10 Sep 2017
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

Réponses (1)

Walter Roberson
Walter Roberson le 10 Sep 2017
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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by