Keep m*n structure after indexing a matrix

I have a matrix (A) and a logical index matrix (i) of the same size. When I do A(i) the result is a Vektor. How can I keep the m*n structure of the Matrix?

 Réponse acceptée

Stephen23
Stephen23 le 2 Août 2016
Modifié(e) : Stephen23 le 2 Août 2016
How would you expect to keep the same "structure" (I guess you mean size) ? If the number of elements that the indexing operation returns is different to the number of elements in the matrix, then the output must have a different size to the input.
If you want to keep all of the elements, you could multiply the matrix by the logical matrix to make certain elements equal to zero:
>> A = randi(9,4,7)
A =
6 9 4 5 8 7 3
8 9 7 5 1 7 4
2 3 2 8 6 8 8
6 6 3 7 9 4 8
>> X = 1==mod(A,2); % detect all odd values
>> A.*X
ans =
0 9 0 5 0 7 3
0 9 7 5 1 7 0
0 3 0 0 0 0 0
0 0 3 7 9 0 0
Or you could turn them into some other value:
>> A(~X) = NaN
A =
NaN 9 NaN 5 NaN 7 3
NaN 9 7 5 1 7 NaN
NaN 3 NaN NaN NaN NaN NaN
NaN NaN 3 7 9 NaN NaN
But every element must have some value, and so you cannot have the output matrix having the same size unless you specify what those elements' values should be.

2 commentaires

Azzi Abdelmalek
Azzi Abdelmalek le 2 Août 2016
Soabon commented
Thank you very much, the multiplication is exactly what I meant.
Thanks for a brilliant yet so simple suggestion.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by