0

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'

SamuelNLP
  • 4,038
  • 9
  • 59
  • 102
  • 2
    Do not do that! There are better approaches than puffing variables into the workspace. http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F look at the third solution – Oleg Aug 23 '13 at 17:33

2 Answers2

1

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.

m_power
  • 3,156
  • 5
  • 33
  • 54
  • It does not work for me, it gives me this error, `The expression to the left of the equals sign is not a valid target for an assignment.` – SamuelNLP Aug 23 '13 at 21:40
0

when calling eval, all arguments must be strings, so convert your cell elements to strings first.

eval([ cellstr(cells{i}) ' = values;']))
Jagte
  • 473
  • 6
  • 15