Search code examples
matlabcell-array

How to insert a number to every cell of a cell array in Matlab?


I have a cell array like this:

    a = {[1 2 3]; [4 5]; [6 7 8 9]};

and want to insert, for example, 10 to the beginning of every cell to have this:

    >> a{:}

    ans =

        10     1     2     3

    ans =

        10     4     5

    ans =

        10     6     7     8     9

Is it possible to do it without any for loop?


Solution

  • You can use CELLFUN with anonymous function:

    b = cellfun(@(x)[10 x],a,'UniformOutput',0)
    

    To answer @tmpearce comment I used a simple script to measure running time:

    a = {[1 2 3]; [4 5]; [6 7 8 9]};
    tic
    a = cellfun(@(x)[10 x],a,'UniformOutput',0)
    toc
    a = {[1 2 3]; [4 5]; [6 7 8 9]}; 
    tic
    for ii=1:numel(a)
        a{ii} = [10 a{ii}];
    end
    toc
    

    The results:

    Elapsed time is 0.002622 seconds.
    Elapsed time is 0.000034 seconds.