Can you explain this behaviour?

2 views (last 30 days)
Ariel Lanza
Ariel Lanza on 21 Jun 2019
Edited: Stephen23 on 21 Jun 2019
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.

Accepted Answer

Stephen23
Stephen23 on 21 Jun 2019
Edited: Stephen23 on 21 Jun 2019
"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,[])

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!