Search code examples
arraysmatlabcell-array

How to initialize a cell array with increasing numbers


How could I initialize a cell array with increasing numbers? For a simple array I can do as follow :

A = [1:0.0001:1.1]

What would be the equivalent for a cell array? How could I obtain:

A = {'1', '1.0001', '1.0002', '1.0003', '1.0004', ...}

Edit:

Here what I have tried so far:

cellfun(@(x) num2str(str2double(x)+0.0001), repmat({'1'},1,21), 'UniformOutput', false)

However, this gives:

{'1.0001', '1.0001', '1.0001',...}

Solution

  • There is a cool undocumented function called sprintfc that prints to cell arrays:

    An = 1:0.0001:1.1;
    As = sprintfc('%g',An)
    

    Example:

    >> A = sprintfc('%g',0:0.2:1)
    A = 
        '0'    '0.2'    '0.4'    '0.6'    '0.8'    '1'
    >> which sprintfc
    built-in (undocumented)
    

    sprintfc was recently highlighted on undocumentedmatlab.com. Yet another great find by Yair Altman. Some other possibilities follow.


    For numerical values, use num2cell:

    A = num2cell(An)
    

    For string representations:

    A = strsplit(num2str(An))
    

    You could also use cellfun:

    A = cellfun(@num2str,num2cell(An),'uni',0)
    

    Or just arrayfun, which is actually simpler:

    A = arrayfun(@num2str,An,'uni',false)