MATLAB: extract submatrix with logical indexing

别等时光非礼了梦想. 提交于 2019-12-05 03:23:59

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')));

Here is a very simple solution:

T = I(any(I'),any(I));
T(:) = M(I);
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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!