Can you explain this behaviour?

2 vues (au cours des 30 derniers jours)
Ariel Lanza
Ariel Lanza le 21 Juin 2019
Modifié(e) : Stephen23 le 21 Juin 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.

Réponse acceptée

Stephen23
Stephen23 le 21 Juin 2019
Modifié(e) : Stephen23 le 21 Juin 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,[])

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by