Two ways of iterating a vector

조회 수: 166 (최근 30일)
Dawid Najda
Dawid Najda 2020년 1월 6일
댓글: Stephen23 2020년 1월 6일
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
Stephen23
Stephen23 2020년 1월 6일
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)

댓글을 달려면 로그인하십시오.

채택된 답변

Mustafa Abu-Mallouh
Mustafa Abu-Mallouh 2020년 1월 6일
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
Dawid Najda
Dawid Najda 2020년 1월 6일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by