1
votes

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

1
remove the zeros that appear in the individual cells Does that mean (1) removing any zero from any cell? (2) Setting to [] any cell that only has zeros? (3) Deleting cells that only have zeros? - Luis Mendo
Remove any zero from any cell please, leaving the overall structure the same (ie. rows of numbers with no zeros). - HCAI
Please edit your question to clarify that, so that it can be useful for future readers - Luis Mendo

1 Answers

2
votes

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);