Two ways of iterating a vector
조회 수: 166 (최근 30일)
이전 댓글 표시
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
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
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!