Search code examples
matlabevalcellcell-array

Create variables from an array of cells in Matlab


I have an array of cells, for example,

cells = {'a', 'b', 'c', d', 'e'};

which is inside a for loop of 1 to 5.

I want to create a variable from a to e depending on the loop index, as 1 to a, 2 to b...

When I try (i is the for index),

eval(cells{i}) = values; it gives me the error,

Undefined function or method 'eval' for input arguments of type 'a'


Solution

  • Here the answer:

    eval(sprintf([cells{i} '=values;']))
    

    And you can remove the ; if you want to see the display in command window.

    In answer to your comment :

    cells = {'a', 'b', 'c', 'd', 'e'};
    values = 4;
    i = 1;
    eval(sprintf([cells{i} '=values;']))
    

    This works perfectly fine on my computer, and i get no warning or error messages.