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

조회 수: 1 (최근 30일)
during my program I want to summon a double variable that it's name saved in a string before!How can do it?

채택된 답변

David Young
David Young 2011년 10월 19일
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.
  댓글 수: 2
Jan
Jan 2011년 10월 19일
The EVAL approach is prone to errors and inefficient. David's suggestion touse a struct is *much* better:
Name = 'xxx'; S.(Name) = rand;

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Daniel Shub
Daniel Shub 2011년 10월 19일
Building on David's answer
xxx = 3;
varname = 'xxx';
val_of_xxx = eval(varname);
can be replaced with
data.xxx = 3;
varname = 'xxx';
val_of_xxx = data.(varname);
The advantage of the latter is it avoids the eval.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by