sam
sam

Reputation: 13

reducing number of 0 rows in matrix using matlab

I have written following program in Matlab

clc;
clear all;
close all;

matrix = [ 0 0 0 0 0 0 0 0;
           0 0 0 0 0 0 0 0;
           0 0 0 0 0 0 0 0;
           1 1 1 1 1 1 1 1;
           1 1 1 0 0 1 1 1;
           0 0 1 1 1 1 1 1;
           0 0 0 0 0 0 0 0;
           0 0 1 1 1 1 1 1;
           0 0 0 0 0 0 0 0;
           0 0 1 1 1 1 1 1;
           1 0 0 1 1 1 1 1;
           1 1 1 0 0 0 1 1];

[row,column] = size(matrix);

for i = 1:row
         if matrix(i,:) == 0
         matrix(i,:) = [];
         end
end
disp(matrix);

what I expect is the 0 rows will be removed in the output matrix. Where as I am getting error

Index in position 1 exceeds array bounds (must not exceed
8).

Error in Untitled (line 21)
         if matrix(i,:) == 0

>> 

Upvotes: 1

Views: 45

Answers (2)

beaker
beaker

Reputation: 16791

As @Cris said, the reason that you're getting an out of bounds error is that you're deleting from the beginning and shrinking the matrix before you check the end.

Another way to fix this is to simply reverse the loop, starting from the end and working toward the beginning. That way, even if you remove a row, its index will never be checked again.

for i = row:-1:1   % loop from last row to first
         if matrix(i,:) == 0
         matrix(i,:) = [];
         end
end

Upvotes: 2

Cris Luengo
Cris Luengo

Reputation: 60444

When you delete a row from the matrix, it no longer has row rows, but row-1. Since you cannot adjust the limits of the loop, you will index out of range. Also, you will skip the row i+1 if you delete row i.

Instead, first find all the rows that need to be deleted, then delete them all at once:

index = all(matrix == 0, 2);
matrix(index,:) = [];

You can of course write that in a single line of code.

Upvotes: 4

Related Questions