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?

 채택된 답변

Stephen23
Stephen23 2016년 8월 2일
편집: Stephen23 2016년 8월 2일

4 개 추천

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

Soabon commented
Thank you very much, the multiplication is exactly what I meant.
Thanks for a brilliant yet so simple suggestion.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2016년 8월 2일

댓글:

2020년 3월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by