Error in storing the values from a loop to a matrix

2 Ansichten (letzte 30 Tage)
HIRAKJYOTI BASUMATARY
HIRAKJYOTI BASUMATARY am 10 Sep. 2017
Beantwortet: Walter Roberson am 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

Antworten (1)

Walter Roberson
Walter Roberson am 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by