What determines the shape of a logically indexed array?

Matlab help explains: " Logical Indexing : ... The output is always in the form of a column vector."
In practice, typing
a = ones(3,3);
b = a([true, true]);
gives a row vector b. Can someone tell me why does it behave this way? And is there any other instance (apart from indexing by one row logical vector) that gives a non-column result? Thanks, O.

 Respuesta aceptada

Ondrej Budac
Ondrej Budac el 7 de Abr. de 2014
Just to complete the story, the answer seems to be:
If B is a logical array and A is any array, then A(B) is equivalent (but faster) way to produce the same result as A(find(B)), including the shape of the output.

Más respuestas (1)

Maybe you need
a = ones(3,3);
b = a([true, true],:)

7 comentarios

Ondrej Budac
Ondrej Budac el 3 de Abr. de 2014
Editada: Ondrej Budac el 3 de Abr. de 2014
I know of several ways how to "enforce" the result to be a column vector. The question is: why the vector in my example isn't?
Since indexing an array is at the very core of every m-file I write, I'd like to understand it.
a = ones(3,3);
a is a 3x3 array
your index is idx=[true, true] is a 1x2 array, the result a(idx) is obviously a 1x2 array.
Ondrej Budac
Ondrej Budac el 3 de Abr. de 2014
Editada: Ondrej Budac el 3 de Abr. de 2014
If that's so obvious, why taking idx = true(2,2) gives a(idx) of size 4x1 and not 2x2?
Azzi Abdelmalek
Azzi Abdelmalek el 3 de Abr. de 2014
Editada: Azzi Abdelmalek el 3 de Abr. de 2014
Ok,
a=[1 2 3 ;4 5 6;7 8 9]
a([4 5;3 1]) % is a 2x2 array
% but if you use logical indexing
a(logical([1 0;1 1]))
% this is equivalent to a([1 2 4])
Ondrej Budac
Ondrej Budac el 3 de Abr. de 2014
Editada: Ondrej Budac el 3 de Abr. de 2014
Well, that's not entirely true. In fact
a(logical([1 0;1 1]))
is equivalent to
a([1; 2; 4])
which brought me to a possible answer of my original question:
The expression A(B) with a matrix A and a logical array B computes (in an faster way) the exact same result as A(find(B)) would give.
Can anyone confirm this? If yes, it would be nice to have it in the help files, since the command find and linear indexing of an array are well-explained.
Just one question, what are you expecting with a(logical([1 0;1 1])) ? The result contains 3 elements
If I now understand logical indexing correctly, I expect a(logical([1 0;1 1])) to give a column vector with values 1, 4, 2, assuming your definition of a.

Iniciar sesión para comentar.

Categorías

Productos

Preguntada:

el 3 de Abr. de 2014

Respondida:

el 7 de Abr. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by