MATLAB Answers

pouya jamali

How to summon a double variable that it's name was stored in a string?

Asked by pouya jamali
on 19 Oct 2011

during my program I want to summon a double variable that it's name saved in a string before!How can do it?



No products are associated with this question.

2 Answers

Answer by David Young
on 19 Oct 2011
 Accepted answer

Use eval. For example

xxx = 3;     % variable with value
varname = 'xxx';    % name of variable stored as a string
% ... other stuff ...
val_of_xxx = eval(varname);   % gets back value of xxx

But think carefully about whether you really need to do this. It's often the case that there's a better way to write your program, perhaps using structure arrays or cell arrays, that avoids having to store variable names as strings. If there is, it's usually much better to avoid using eval.


Jan Simon
on 19 Oct 2011

The EVAL approach is prone to errors and inefficient. David's suggestion touse a struct is *much* better:
Name = 'xxx'; S.(Name) = rand;

Thanks a lot

Answer by Daniel Shub
on 19 Oct 2011

Building on David's answer

xxx = 3;
varname = 'xxx';
val_of_xxx = eval(varname);

can be replaced with = 3;
varname = 'xxx';
val_of_xxx = data.(varname);

The advantage of the latter is it avoids the eval.

  1 Comment

Thanks a lot Dani:-)

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!