Search code examples
arraysmatlabcell

Zeroing a cell array of irregular size in MATLAB


I have a cell array M of irregular size, something like:

>> M

    M = 
        [1x7 double]
        [1x9 double]
        [1x14 double]
        [1x6 double]

I would like to set to zero all the elements of the cell without looping through them. I already tried to use deal, as suggested here for a case where all the array of the cell have the same dimension, but with no success.

Any idea of how to elegantly do it, with cellfun for example? Thank in advance ;)


Solution

  • How about this:

    MM = cellfun(@(c) zeros(size(c)), M, 'UniformOutput',false);
    

    If you only want to "zero out" certain cells, you can apply still apply indexing:

    M(idx) = cellfun(@(c) zeros(size(c)), M(idx), 'UniformOutput',false);
    

    Also for-loops are not so bad:

    for i=1:numel(M)
        M{i}(:) = 0;
    end