Search code examples
matlabloopsiterationcell-array

Matlab: iterate 2d cell array and map each row to variables


I'm new to Matlab, I want to have a set of different parameters to initialize the computations and then plot the result for each of them. I'm trying the following code:

params_set = {{0, '-'}, {20, '--'}, {50, '-o-'}};

for params = params_set
    [param, stroke] = deal(params{:})
    % do something - i.e. solve equation and plot result with given stroke settings
end

I expect the variable "param" to be 0, then 20, then 50 respectively and the variable "stroke" to be '-', '--', and finally '-o-'.

But instead I get the following:

param = 

    [0]    '-'


stroke = 

    [0]    '-'


param = 

    [20]    '--'


stroke = 

    [20]    '--'


param = 

    [50]    '-o-'


stroke = 

    [50]    '-o-'

What am I missing there?


Solution

  • The for loop iterates over (columns of) cells, not over cell's contents. So in each iteration params is a nested (two-level) cell array. For example, in the first iteration params is {{0, '-'}}.

    Therfore you need {1} to "unbox" the outer cell into the inner cell, and then {:} to unbox the inner cell into its contents (number and string):

    [param, stroke] = deal(params{1}{:})
    

    Note also that in recent Matlab versions you can remove deal:

    [param, stroke] = params{1}{:}
    

    although it's probably a good idea to leave it there.

    So the code would be:

    params_set = {{0, '-'}, {20, '--'}, {50, '-o-'}};
    for params = params_set
        [param, stroke] = deal(params{1}{:})
        % do something - i.e. solve equation and plot result with given stroke settings
    end