Trim binary matrix in MatLab

I have a binary matrix like this:

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

and I want to crop this matrix (in other words, remove zeros at the borders) so that it looks like this:

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

How to do Matlab? that do not use regular loops and conditions .

To be more precise , the matrix should be reduced to start with the first column, which has at least one 1, and ends in the last column with the same condition, inclusive. Any column in this range must be removed. For strings, the same rules apply.

Thank.

+5
source share
3 answers

If you have data in the matrix M...

x = find(any(M,2),1,'first'):find(any(M,2),1,'last');
y = find(any(M),1,'first'):find(any(M),1,'last');
M(x, y)

, , / 1, :

M(any(M,2), any(M))
+9

, find :

[r1, c1] = find(x, 1, 'first')
[r2, c2] = find(x, 1, 'last')
x(r1:r2, c1:c2)
0

Expanding to taller sizes:

Assuming that a three-dimensional matrix needs to be cropped, it is simpler:

M=rand(3,3,3); % generating a random 3D matrix
M(2,:,:)=0; % just to make a check if it works in extreme case of having zeros in the         middle

padded = padarray(M,[2 2 2]); % making some zero boundaries

[r,c,v]=ind2sub(size(padded),find(padded));

recoveredM=padded(min(r):max(r),min(c):max(c),min(v):max(v));

check=M==recoveredM  % checking to see if M is successfully recovered 
0
source

All Articles