MATLAB: extract submatrix with logical indexing

foglerit picture foglerit · Jul 10, 2012 · Viewed 12.6k times · Source

I'm looking for an elegant solution to this very simple problem in MATLAB. Suppose I have a matrix

>> M = magic(5)

M =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9 

and a logical variable of the form

I =

     0     0     0     0     0
     0     1     1     0     0
     0     1     1     0     0
     0     0     0     0     0
     0     0     0     0     0

If I try to retrieve the elements of M associated to 1 values in I, I get a column vector

>> M(I)

ans =

     5
     6
     7
    13

What would be the simplest way to obtain the matrix [5 7 ; 6 13] from this logical indexing?

If I know the shape of the non-zero elements of I, I can use a reshape after the indexing, but that's not a general case.

Also, I'm aware that the default behavior for this type of indexing in MATLAB enforces consistency with respect to the case in which non-zero values in I do not form a matrix, but I wonder if there is a simple solution for this particular case.

Answer

nrz picture nrz · Jul 10, 2012

This is a one way to do this. It is assumed that all rows of I have same number of ones. It is also assumed that all columns of I have same number have ones, because Submatrix must be rectangular.

%# Define the example data.

M = magic(5);
I = zeros(5);
I(2:3, 2:3) = 1;

%# Create the Submatrix.

Submatrix = reshape(M(find(I)), max(sum(I)), max(sum(I')));