MATLAB: extract a sub-matrix with logical indexing

I am 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 boolean form variable

 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 extract the elements of M associated with the values 1 in I , I get a column vector

 >> M(I) ans = 5 6 7 13 

What will be the easiest way to get the matrix [5 7 ; 6 13] [5 7 ; 6 13] from this logical indexing?

If I know the form of non-zero elements of I , I can use the transformation after indexing, but this is not a general case.

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

+8
matrix indexing matlab submatrix
source share
3 answers

This is one way to do this. It is assumed that all rows from I have the same number of units. It is also assumed that all columns of I have the same number, since the 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'))); 
+11
source share

Here is a very simple solution:

 T = I(any(I'),any(I)); T(:) = M(I); 
+3
source share
 M = magic(5); I = [ ... ]; ind = find(I); %# find indices of ones in I [y1, x1] = ind2sub(size(M), ind(1)); %# get top-left position [y2, x2] = ind2sub(size(M), ind(end)); %# get bottom-right position O = M(y1:y2, x1:x2); %# copy submatrix 
+2
source share

All Articles