Search code examples
arraysmatlabcell-array

Assign different values to cell arrays in MATLAB at once


I need help on creating a cell array in MATLAB where each cell is an array of different sizes. For example, let's assume I have this simple array and the value:

A = [5 3 8 7 0 4 1];
B = 10;

The cell array C must be created such that:

C = 
[10 20 30 40 50]
[10 20 30]
[10 20 30 40 50 60 70 80]
[10 20 30 40 50 60 70]
[Empty matrix 1x0]
[10 20 30 40]
[10]

Is it possible to do that in one operation only? I have tried:

C = cellfun(@(a,b)b*ones(1,a), A,B)

but it did not work.


Solution

  • cellfun expects a cell array as the input into the function. You have a numeric array so use arrayfun instead. You are also not outputting a scalar per element in the array so you need to set the UniformOutput flag to 0. Finally, use the colon operator to do what you need instead of matrix multiplication. The output will unfortunately be a row vector of cells so if you absolutely need a column vector such as what you have shown in your post, transpose the output:

    A = [5 3 8 7 0 4 1];
    B = 10;
    C = arrayfun(@(x) B*(1:x), A, 'UniformOutput', 0).';
    

    Take note that the anonymous function declared as the first input into arrayfun has lexical scope, meaning that any variables that were visible in the workspace before the anonymous function declaration is visible. You can just access that variable inside your function instead of having to manually feed it into arrayfun as a separate input.

    We now get:

    >> format compact
    >> celldisp(C)
    C{1} =
        10    20    30    40    50
    C{2} =
        10    20    30
    C{3} =
        10    20    30    40    50    60    70    80
    C{4} =
        10    20    30    40    50    60    70
    C{5} =
         []
    C{6} =
        10    20    30    40
    C{7} =
        10