Search code examples
matlabtypescell-array

Matlab: how to use numeric arrays such as 1:2 to create a cell array such as {1,2}?


I want to use the numeric array such as 1:7 to create a cell array such as {1,2,3,4,5,6,7}. How can I do it? By which function?

Wrong

>> {1:2}

ans = 

    [1x2 double]

Correct output

>> {1,2}

ans = 

    [1]    [2]

Solution

  • You can use

    num2cell(1:7)
    

    which converts every number to a single element in the output cell.

    There are more things you can do with it; type help num2cell for more info.

    There's a bunch of alternative approaches, the easiest I think would be

    arrayfun(@(x)x, 1:7, 'UniformOutput', false)
    

    or the good old for loop:

    N = 7;
    
    C = cell(N,1);
    for ii = 1:N
        C{ii} = ii; end
    

    Despite what you hear about for loops in MATLAB, they are not so terrible anymore. If you repeat Nick's test for larger N, you'll see that num2cell is fastest, then the for loop, and then arrayfun.