Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim Binary Matrix in MatLab

Tags:

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 trim this matrix (in other words, remove zeroes at the boundaries) to be like:

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

How to do this the "Matlab" way? that's not to use conventional loops and conditions.

To be clearer, the matrix should be reduced to start from the first column which has at least one 1, and ends at the last column with the same condition, inclusive. Any column out of this range should be removed. Same rules apply for rows.

Thanks.

like image 431
Ahmed Khalaf Avatar asked Feb 22 '13 15:02

Ahmed Khalaf


2 Answers

If you have the data in 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)

Or, if you know that there will be a 1 in every row/col except the edges:

M(any(M,2), any(M))
like image 133
shoelzer Avatar answered Nov 15 '22 06:11

shoelzer


Extension to higher dimensions:

Assuming a 3D matrix to be trimmed, this is more straightforward:

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 
like image 31
Arash Avatar answered Nov 15 '22 07:11

Arash