Search code examples
matlabcell

How to remove zeros from a cell array in MATLAB


I have a cell called sequences (406 x 1) where each cell is (1x25 double).

sequences=randi(5,406,25); #create an array with values max 5, 406x25
sequences(50:65,5)=0; #Add zeros
sequences=num2cell(sequences,2); #convert to cell

I would like to remove any zeros from any cell, keeping the structure the same (just removing the individual zeros). I've tried every answer from stack and mathworks, but nothing will shift them.

e.g. 1

idxZeros = cellfun(@(c)(isequal(c,0)), sequences);
sequences(idxZeros) = [];

Doesn't change anything about the cell at all.

e.g. 2

zero_idx = bsxfun(@eq, [sequences{:}], 0);
sequences(zero_idx) = {[]};

e.g.3

 sequences([sequences{:}]==0)={[]};

deletes a load of cells

Note: I don't mind leaving it as an array, deleting zeros and reshaping, but I do need a cell at the end of it. Any thoughts would be much appreciated


Solution

  • This removes any zero from any cell, leaving the results in each cell as a row vector:

    result = cellfun(@(x) nonzeros(x).', sequences, 'UniformOutput', false);
    

    Or you can replace nonzeros by logical indexing:

    result = cellfun(@(x) x(x~=0), sequences, 'UniformOutput', false);