Keep m*n structure after indexing a matrix

10 views (last 30 days)
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?

Accepted Answer

Stephen23
Stephen23 on 2 Aug 2016
Edited: Stephen23 on 2 Aug 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 Comments
Azzi Abdelmalek
Azzi Abdelmalek on 2 Aug 2016
Soabon commented
Thank you very much, the multiplication is exactly what I meant.
Mohamed Abdelhamid
Mohamed Abdelhamid on 12 Mar 2020
Thanks for a brilliant yet so simple suggestion.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!