Is it possible to set a variable by its name?

조회 수: 3 (최근 30일)
Mr M.
Mr M. 2015년 6월 10일
편집: Stephen23 2019년 6월 19일
I would like to make a for cycle, but the running variable should be defined by the user. For example:
params = [1,2,5,7,13]
for i=1:length(params)
v = params(i);
% or x = params(i);
% or y = params(i);
end
So v, x, or y should be choosen by its name, for example from the information contained in a string: my_string = 'v';
  댓글 수: 1
Stephen23
Stephen23 2015년 6월 10일
편집: Stephen23 2015년 6월 10일
Use Ingrid's solution (a switch statement) or a structure with dynamic field names, or perhaps a non-scalar structure, or even functions (making internal operations independent from the input variable names). All of these would be much more robust than using dynamic variables.
Do not create variables dynamically, because this is a really bad programming practice that is buggy, slow, and removes lots of inbuilt code checking, amongst other disadvantages...
Although beginners seem to love variables magically popping in and out of workspaces, if you learn to not create dynamically named variables and instead use more robust programming practices then your code becomes much more reliable.

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

답변 (2개)

Ingrid
Ingrid 2015년 6월 10일
you can use a switch - case statement
for i = 1:length(params)
switch my_string
case 'v'
v = params(i);
case 'x'
x = params(i);
case 'y'
y = params(i);
otherwise
error('Unrecognized string name');
end
end
  댓글 수: 1
Mr M.
Mr M. 2015년 6월 10일
Yes, switch is a possible solution, but lot of space and coding, and very rigid. It would be nice to make it automatically instead of writing down all variable names at least twice.

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


Stephen23
Stephen23 2015년 6월 10일
편집: Stephen23 2019년 6월 19일

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by