Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove rows that contain zeros from cells array in matlab

Tags:

matlab

cells

I have a cell array resulted from a certain code as follows:

m = 

    [         0]    'GO:0008150'
    'GO:0008150'    'GO:0016740'
    'GO:0016740'    'GO:0016787'
    'GO:0016787'    'GO:0006810'
    'GO:0008150'    'GO:0006412'
    'GO:0016740'    'GO:0004672'
    'GO:0016740'    'GO:0016779'
    'GO:0016787'    'GO:0004386'
    'GO:0016787'    'GO:0003774'
    'GO:0016787'    'GO:0016298'
    'GO:0006810'    'GO:0016192'
    'GO:0006412'    'GO:0005215'
    'GO:0004672'    'GO:0030533'
    [         0]    'GO:0008150'
    [         0]    'GO:0016740'
    'GO:0008150'    'GO:0016787'
    'GO:0008150'    'GO:0006810'
    'GO:0006810'    'GO:0006412'
    [         0]    'GO:0004672'
    [         0]    'GO:0016779'
    [         0]    'GO:0004386'
    'GO:0016192'    'GO:0003774'
    [         0]    'GO:0016298'
    [         0]    'GO:0016192'
    'GO:0006810'    'GO:0005215'
    'GO:0005215'    'GO:0030533'

I need to remove the rows which contains zero (for example: row one should be deleted because we have a zero in the first column). so how can I create an array from this array that doesn't contain zeros?

like image 801
Gloria Avatar asked Feb 18 '23 17:02

Gloria


2 Answers

You can do this in a pretty one-liner:

m(any(cellfun(@(x)x(1)==0, m),2), :) = []

Alternatively:

m(any(~cellfun(@ischar, m),2), :) = []

which is a tad faster.

If you can be certain that only the first column will ever contain a zero, use

m = m(cellfun(@ischar, m(:,1)),:)

and, finally, you can use

m = m(cellfun('isclass', m(:,1), 'char'),:)

which looks "old", but actually has greater performance.

Testing these one thousand times on your example array, gives

Elapsed time is 1.382801 seconds.
Elapsed time is 0.138519 seconds.
Elapsed time is 0.075245 seconds.
Elapsed time is 0.014674 seconds.
like image 85
Rody Oldenhuis Avatar answered Mar 08 '23 11:03

Rody Oldenhuis


  zerosLocation = cellfun(@(x)isEqual(x, 0 ) , m);
  zeroRows = any(zerosLocation,2);
  m(zeroRows,:) = [];
like image 45
Andrey Rubshtein Avatar answered Mar 08 '23 13:03

Andrey Rubshtein