Can you explain this behaviour?
1 回表示 (過去 30 日間)
古いコメントを表示
I am running this code as a script
vect = [1;1];
for iter = find(vect==1)
[rowindex,colindex] = ind2sub(size(vect),iter);
fprintf('%s, %d, %d\n','AnyString', rowindex, colindex);
end
And I would expect this output
>> ZX_provascript
AnyString, 1, 1
AnyString, 1, 2
>>
Instead I get
>> ZX_provascript
AnyString, 1, 2
, >>
If I simplify the code it does work. For example, if I do not print the string, I get the output
>> ZX_provascript
1, 2
1, 1
>>
Which is acceptable (I know that sometimes the order of stdout can change).
If I manually set rowindex and colindex it works correctly.
If I choose a row vector as vect it works correctly.
Is this a MATLAB bug?
I am running MATLAB '9.4.0.813654 (R2018a)' on Windows 7.
0 件のコメント
採用された回答
Stephen23
2019 年 6 月 21 日
編集済み: Stephen23
2019 年 6 月 21 日
"Is this a MATLAB bug?"
Sadly no, it is a documented "feature".
The reason is because for does not actually iterate over the elements of the values array, as most users think, it actually iterates over the columns of the values array. This is explained in the for documentation: "valArray — Create a column vector, index, from subsequent columns of array valArray on each iteration." You provided a 2x1 values array (i.e. one column, the output of find), your for loop actually only iterates once, with iter==[1;2]
I have never seen anyone use this "feature" in any useful way, but it causes plenty of problems.
You can easily avoid this "feature" by reshaping the values array into a row vector:
for iter = reshape(find(vect==1),1,[])
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!