Why does a for loop iterate over an empty column vector?

7 ビュー (過去 30 日間)
Scott
Scott 2022 年 8 月 25 日
回答済み: Bruno Luong 2022 年 8 月 25 日
A for loop in my code was executing unexpectedly. I had provided it with an empty column vector, and I had supposed that it would not execute. However it does iterate once, as this simple example shows:
>> bob = intersect([1;2;3],[4;5;6])
bob =
0×1 empty double column vector
>> for ii = bob; disp('executed an iteration'); end
executed an iteration
This behavior is not observed when iterating over an empty vector or an empty row vector, as shown below:
>> for ii = []; disp('executed an iteration'); end
>> fred = intersect([1,2,3],[4,5,6])
fred =
1×0 empty double row vector
>> for ii = fred; disp('executed an iteration'); end
Is this expected and/or desired behavior for a for loop to iterate over an empty column vector?

採用された回答

Matt J
Matt J 2022 年 8 月 25 日
編集済み: Matt J 2022 年 8 月 25 日
Yes, I'm sure it's expected. There will be as many iterations as there are columns of "bob".
k=0;
for bob=zeros(0,5)
k=k+1,
end
k = 1
k = 2
k = 3
k = 4
k = 5

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2022 年 8 月 25 日
Yes this is expected.
The for-loop iterates on the number of columns of an array, regardless the number of row
for c = A
...
end
is equivalent to
for j=1:size(A,2)
c = A(:,j);
...
end

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by