Delete rows containing zeros from an array of cells in matlab

I have an array of cells derived from specific 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 delete rows that contain zero (for example: the row must be deleted because there is zero in the first column). so how can i create an array from this array that does not contain zeros?

+4
source share
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 little faster.

If you can be sure that only the first column will contain 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 great performance.

Testing these thousands of times in your array of examples 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. 
+6
source
  zerosLocation = cellfun(@(x)isEqual(x, 0 ) , m); zeroRows = any(zerosLocation,2); m(zeroRows,:) = []; 
+2
source

Source: https://habr.com/ru/post/1442084/


All Articles