Two ways of iterating a vector

32 visualizaciones (últimos 30 días)
Dawid Najda
Dawid Najda el 6 de En. de 2020
Comentada: Stephen23 el 6 de En. de 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 comentario
Stephen23
Stephen23 el 6 de En. de 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)

Iniciar sesión para comentar.

Respuesta aceptada

Mustafa Abu-Mallouh
Mustafa Abu-Mallouh el 6 de En. de 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 comentario
Dawid Najda
Dawid Najda el 6 de En. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by