Search code examples
arraysmatlabplotfindcell-array

Return the cells in a cell array that don't contain all zeros in matlab


I have a cell array A with many cells, and each cell has 50 values. The cells either have all zeros, or a combination of other numbers.

I'm looking for a way to figure out which cells do NOT have all zeros, as I want to plot those in a graph. If I try to plot all of the cells in the cell array, it's way too much for matlab to handle. So ideally, I'd get a list, for example, of A{1}, A{53}, A{235}, etc., that aren't composed of all zeros.

When looking on here, I found how to find the nonzero values in an array or matrix, but I didn't see anything about finding cells with nonzero values.

Thanks so much for any and all help!


Solution

  • Let's consider the example data

    a=[{randi(10,1,50)} {randi(10,1,50)} {zeros(1,50)} {randi(10,1,50)}]
    

    Then you can find the indexes of the cells that do not exclusively contain zeros like this:

    nonzeroind=find(~cellfun(@(x) all(x==0),a))
    

    If the matrices stored in the cells have more than one none-singleton-dimension, you will have to apply all as many times as you have dimensions in your highest dimension cell like this:

    nonzeroind=find(~cellfun(@(x) all(all(x==0)),a))
    

    The sizes of the matrices stored in the cells don't matter with this approach.