How to extract matrix elements corresponding to a logical matrix?

9 views (last 30 days)
Suppose I've a matrix A - (204 x 245) which has values (0-3) at certain locations. Value 2 is located in this matrix in the shape of a rectangle (see attached image). I want to extract the portion of MATRIX where 2 appears. First I tried using logical indexing which generates correct logical matrix (containing 0/1), let's call it 'P'. When I pass that logical matrix (P) as an argument to the original matrix (A), it gives me a (double) matrix of order (80X1). I wanted the output (of order: 8 x 10 as apparent in figure) in the form of (double) matrix, not as vector.
P = A == 2; % Logical indexing (output: 204 x 245)
Q = A(P); % Gives vector off type double (80 x 1)
% Required?
% A(37:44 , 76:85)
I also tried find() to extract row & column indices but still couldn't get the required matrix. Perhaps I'm doing something wrong :( Kindly guide me in this regard.
P.S: The coding is dynamic so a solution like A(37:44 , 76:85) is useless

Accepted Answer

Matt J
Matt J on 28 Jul 2023
P=(A==2);
Q=A(any(P,2), any(P,1))

More Answers (1)

Matt J
Matt J on 28 Jul 2023
[I,J]=find(A==2);
Q=A(min(I):max(I), min(J):max(J));

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!