Take the 2-minute tour ×

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?

share|improve this question
From your example, and as @Rody Oldenhuis implicitly highlights, this is better suited as finding char vs. double instead of a zero vs. non-zero) –  gevang Oct 25 '12 at 15:15
add comment

2 Answers

up vote 6 down vote accepted

You can do this in a pretty one-liner:

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


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.
share|improve this answer
Good effort with the performance tests.. –  angainor Oct 26 '12 at 18:57
add comment
  zerosLocation = cellfun(@(x)isEqual(x, 0 ) , m);
  zeroRows = any(zerosLocation,2);
  m(zeroRows,:) = [];
share|improve this answer
add comment

Your Answer


