Two ways of iterating a vector

73 ビュー (過去 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 Center および File ExchangeLoops 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