Search code examples
matlabloopscell-array

matlab: delete zero rows from each matrix in cell-array without loop


I have a cell array looks like this:

>> celldisp(C)

C{1} = 

 4     2     7    10
 0     0     0     0
 0     0     0     0
 0     0     0     0
 0     0     0     0

C{2} =

 4     2     7    10
 8     2     8     8
 0     0     0     0
 0     0     0     0
 0     0     0     0 

C{3} =

 4     2     7    10
 8     2     8     8
 8     4     1     6
 0     0     0     0
 0     0     0     0

C{4} =

 4     2     7    10
 8     2     8     8
 8     4     1     6
 3     1     3     4
 0     0     0     0 

C{5} =

 4     2     7    10
 8     2     8     8
 8     4     1     6
 3     1     3     4
 3     2     3     9

Now I want to delete all the rows which are filled with zeros, so I can get the cell looks like this:

C{1} =

 4     2     7    10

C{2} =

 4     2     7    10
 8     2     8     8

C{3} =

 4     2     7    10
 8     2     8     8
 8     4     1     6

C{4} =

 4     2     7    10
 8     2     8     8
 8     4     1     6
 3     1     3     4

C{5} =

 4     2     7    10
 8     2     8     8
 8     4     1     6
 3     1     3     4
 3     2     3     9

How can I do this without any loop? PS: I'm trying to use

'cellfun(@(c_el) nonZeros(c_el), C,'UniformOutput',false)' 

But matlab shows

Undefined function 'nonZeros' for input arguments of type 'double'. 
Error in @(c_el)nonZeros(c_el)' 

so is there any brilliant way to fix the questions? Thanks.


Solution

  • As the other answer mentions, you need to use nonzeros but even if you do that, the order of the output wont be preserved. Instead, you could

    Try this:

    out = cellfun(@(x) x(any(x,2),:),C,'UniformOutput',false);
    

    Display the cell array using celldisp

    celldisp(out);