Two ways of iterating a vector

36 visualizzazioni (ultimi 30 giorni)
Dawid Najda
Dawid Najda il 6 Gen 2020
Commentato: Stephen23 il 6 Gen 2020
I have a problem with iterating a vector.
Here is part of my code (values of Best, Choices and Follower are not hardcoded ofc, I just put them not to include the entire file)
Best = 3;
Choices = [1;2];
Follower = [0;1];
for iter = 1:length(Choices)
fprintf('i=%i\n', Choices(iter))
fprintf('outcome=(%f, %f)\n', Best, Follower(Choices(iter)))
end
for item = Choices
fprintf('i=%i\n', item)
fprintf('outcome=(%f, %f)\n', Best, Follower(item))
end
When iterating by index, it works properly (result is the same as analytical solution of the problem):
i=1
outcome=(3.000000, 0.000000)
i=2
outcome=(3.000000, 1.000000)
But when I try to iterate over values, the result is:
i=1
i=2
outcome=(3.000000, 0.000000)
outcome=(1.000000, >>
So the lines are mixed, value of Best changes? or is missing? and the last fprintf doesn't finish...
Please explain if I am doing something wrong, misunderstood sth or is it a bug?
I just noticed that the second version works properly for horizontal vectors ( eg. [1 2] instead of [1;2])...
  1 Commento
Stephen23
Stephen23 il 6 Gen 2020
Note that this is simple and efficient without a loop:
>> M = [1,2;3,3;0,1]
M =
1 2
3 3
0 1
>> fprintf('i=%i\noutcome=(%f,%f)\n',M)
i=1
outcome=(3.000000,0.000000)
i=2
outcome=(3.000000,1.000000)

Accedi per commentare.

Risposta accettata

Mustafa Abu-Mallouh
Mustafa Abu-Mallouh il 6 Gen 2020
In MATLAB, the for loop iterates over columns. When you define item as Choices, you're defining it as a single column. Change your loop to begin with
for item = Choices'
fprintf('i=%i\n', item)
fprintf('outcome=(%f, %f)\n', Best, Follower(item))
end
And it will work properly.
You could also define Choices as a row vector from the start.
See here for more information.
  1 Commento
Dawid Najda
Dawid Najda il 6 Gen 2020
Oh right, I changed the definition to
Follower = zeros(1, hght);
and then the part that fills it accepted it, and iterating worked too.
Thanks for the explaination.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by