Logical Indexing via multiplication

Hi,
I have a 3 x 3 matrix, B = [ 1 2 3; 4 5 6; 7 8 9 ]
I have a matrix, A = [ 0 1 0 ]'.
How can I extract only the middle row of matrix B, ie. [ 4 5 6] ?
If I multiply, I get the first and third row with zeros.
This is a simplification of a larger problem. How can I do it via multiplication of A and B?
I want all the rows of B that correspond where the index A equals 1.
Any help would be appreciated!
Thank you,
Inna

1 comentario

Basic logical indexing:
B = [1,2,3;4,5,6;7,8,9];
A = [0;1;0];
C = B(A==1,:)
C = 1×3
4 5 6

Iniciar sesión para comentar.

 Respuesta aceptada

David Goodmanson
David Goodmanson el 21 de Dic. de 2020
Editada: David Goodmanson el 21 de Dic. de 2020

0 votos

Hi Inna, not done by multiplication, but:
ind = find(A==1)
rows_you_want = B(ind,:)
the colon means to take every column in whatever rows are selected.

3 comentarios

Inna Pelloso
Inna Pelloso el 21 de Dic. de 2020
Editada: Inna Pelloso el 21 de Dic. de 2020
This is a simplification of a larger problem. How can I do it via multiplication of A and B?
I want all the rows of B that correspond where the index A equals 1.
Thank you!
Inna Pelloso
Inna Pelloso el 21 de Dic. de 2020
Thank you. For some reason, I ALWAYS forget about using the find function.
Stephen23
Stephen23 el 21 de Dic. de 2020
Editada: Stephen23 el 21 de Dic. de 2020
FIND is not required, logical indexing is simpler and more efficient:
ind = A==1;
rows_you_want = B(ind,:)

Iniciar sesión para comentar.

Más respuestas (1)

Walter Roberson
Walter Roberson el 21 de Dic. de 2020
Editada: Walter Roberson el 21 de Dic. de 2020

1 voto

This is a task that cannot be done by multiplication.
If you use .* elementwise multiplication then the size of the result is max() of the sizes of the inputs provided they are compatible sizes. Saying max() takes into account implicit expansion. The size of output never depends on the content of the data when you use .*
If you use A*B then size(A, 2) must equal size(B, 1) and the size of the output is always size(A, 1) by size(B, 2) no matter what the content of the variables are.
You can create projection matrices that select specific rows, but the size of the matrices depend on the number of rows being selected, so they have to be constructed outside of plain matrix multiplication.

1 comentario

P = eye(size(B))
P = P(logical(A), :)
C = P * B
But you cannot construct P using just matrix multiplication without making decisions based on the content of A

Iniciar sesión para comentar.

Categorías

Etiquetas

Preguntada:

el 21 de Dic. de 2020

Editada:

el 21 de Dic. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by