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.

采纳的回答

Stephen23
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 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by