7

I have a cell array in MATLAB, lets say cell_arr and it has zero entries as well as non-zeros cell entries. For example:

cell_arr = {0, 0, 0, 0, 0, {1x3 cell}, {1x3 cell}, {1x3 cell}, {1x3 cell}};

Can somebody please tell how to remove these zero entries from the cell_arr or, to find the indices of non-zero entries? Additionally, I want to avoid for loop for performing this job.

I already tried find function, however, find function is not applicable for cell arrays. I am wondering if there exists a single line statement/expression doing this job?

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
Sanchit
  • 3,180
  • 8
  • 37
  • 53

2 Answers2

8

As far as I know there is no single line function. You have to combine some functionallity. The first line finds the zeros in your cell array, while the second line deletes those entries. Note the () parentheses i.s.o. {} for removal.

Try this:

idxZeros = cellfun(@(c)(isequal(c,0)), cell_arr);
cell_arr(idxZeros) = [];
Nick
  • 3,143
  • 20
  • 34
  • 4
    Using the function `isequal(c,0)` avoids using the two tests `~iscell(c) && c == 0` – marsei Sep 11 '13 at 12:28
  • @Magla true, however I think this is easier to debug, as one should understand that whenever the first test fails the second test will not be executed. – Nick Sep 11 '13 at 12:54
  • 1
    @Nick: I see nothing hard to debug about `C_pruned = C(~cellfun(@(x)isequal(x,0), C))`...Still, +1 :) – Rody Oldenhuis Sep 11 '13 at 13:42
  • @Nick I concur with Rody. `isequal(c, 0)` is just as easy to read/debug, and it's a more general solution than using `~iscell(c)`. If the cell array contains objects which are not cells and not zeros, `c == 0` might trigger an error. – Eitan T Sep 11 '13 at 13:43
  • @Nick: plus, what if there are not zeros in the cell, but null-characters (`char(0)`))? Your test would yield false positives, while `isequal` would be correct. – Rody Oldenhuis Sep 11 '13 at 13:45
  • 1
    @EitanT & Rory, those are things I did not think off. Thanks! – Nick Sep 11 '13 at 13:51
0
cell_arr(cellfun(@(x) ~x(1),cell_arr(:,1)),:) = []

Please let me know if this works.

Yunus
  • 63
  • 4