Can you explain this behaviour?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Ariel Lanza
el 21 de Jun. de 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.
0 comentarios
Respuesta aceptada
Stephen23
el 21 de Jun. de 2019
Editada: Stephen23
el 21 de Jun. de 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,[])
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!