Products

3 Answers

Here is my implementation. Let me know if there is something you do not understand.

[r,c] = size(a);

% Starts at bottom row and removes rows that have nothing in them.
for i = fliplr(1:r)
if sum(a(i,:)) == 0
a(i,:) = [];
else
break;
end
end

% Starts from right-most column and removes columns with nothing in them.
for i = fliplr(1:c)
if sum(a(:,i)) == 0
a(:,i) = [];
else
break;
end
end

% Starts at top row, counts number of empty rows until it gets to a
% non-empty row. These cannot be removed immediately or it will screw up
% the for-loop.
top_count = 0;
for i = 1:r
if sum(a(i,:)) == 0
top_count = top_count + 1;
else
break;
end
end

% Starts at left-most column, counts number of empty columns until it gets
% to a non-empty column. These cannot be removed immediately or it will
% screw up the for-loop.
left_count = 0;
for i = 1:c
if sum(a(:,i)) == 0
left_count = left_count + 1;
else
break;
end
end

% Now left-most empty columns and top empty rows can be safely removed.
if top_count > 0
a(1:top_count,:) = [];
end
if left_count > 0
a(:,1:left_count) = [];
end