Removing zero rows from a matrix

  • Thread starter Thread starter mikeph
  • Start date Start date
  • Tags Tags
    Matrix Zero
Click For Summary
SUMMARY

The discussion focuses on removing rows containing only zeros from a matrix in MATLAB. The solution provided uses the syntax a(all(a==0,2),:)=[] to eliminate these rows. The user also inquires about generating a second matrix b without zero rows, which is not achieved correctly in their attempt. An alternative method using a while loop is suggested to avoid issues with changing matrix size during iteration.

PREREQUISITES
  • Understanding of MATLAB syntax and operations
  • Familiarity with matrix manipulation in MATLAB
  • Knowledge of logical indexing in MATLAB
  • Basic programming concepts, particularly loops and conditionals
NEXT STEPS
  • Learn about MATLAB logical indexing techniques
  • Explore MATLAB matrix manipulation functions
  • Study the differences between while loops and for loops in MATLAB
  • Investigate the use of empty arrays in MATLAB
USEFUL FOR

MATLAB users, data analysts, and anyone involved in matrix operations who needs to efficiently manage and manipulate data structures in MATLAB.

mikeph
Messages
1,229
Reaction score
18
say,

Code:
a = [1,2,3; 0,0,0; 0,4,5];

how can I remove the rows of a that contain only zeros?

I found a link which works, but I don't know why:
http://www.mathworks.in/matlabcentral/newsreader/view_thread/281578
Suggesting:
Code:
a(all(a==0,2),:)=[]

1. what does the "=[]" syntax do
2. can this method be used to generate a second matrix b = a(without any zero rows)? I tried re-writing in this form and it doesn't work:

Code:
>> b = a(all(a==0,2),:)
b =
     0     0     0

Clearly I'm missing something,
Thanks
 
Physics news on Phys.org
If you want something that's a bit less cryptic and a bit more transparent you could do it like this

Code:
k=0; rows=size(a)(1)
while (k<rows)
   k=k+1;
   if all(a(k,:)==0)
      a(k,:)=[];
      rows=rows-1;
   end
end

Note that you can't use a "for" loop because if a row is removed then it will reduce the size of the matrix, causing the for loop index to eventually exceed the size of the matrix. This problem of course only arises because you're processing the matrix "in place".

BTW, [] just represents an empty vector.
 
Last edited:

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
8K
  • · Replies 32 ·
2
Replies
32
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
7K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 14 ·
Replies
14
Views
3K