How do you set a variable name to a variable value?

조회 수: 87 (최근 30일)
JIWON LEE
JIWON LEE 2021년 8월 6일
댓글: Stephen23 2021년 8월 6일
If I make a variable ( a = 'name' ), I want to set the variable name with the value of a.
ex) ( name = )
  댓글 수: 4
KSSV
KSSV 2021년 8월 6일
John = 3 ;
This is enough right.
Stephen23
Stephen23 2021년 8월 6일
Before you force yourself into writing slow, inefficient, complex code that is difficult to debug, you should read this:

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

채택된 답변

Dave B
Dave B 2021년 8월 6일
편집: Dave B 2021년 8월 6일
You can do this with eval, but you are likely to regret this.
a = 'Pi';
val = pi;
eval(a + " = " + val);
Pi = 3.1416
This link has some alternatives to using string evaluation to run code. It's a bad/dangerous style and there's almost always a better approach.
If you must name your variables with another variable, consider using fields of a struct rather than raw variables:
mydynvars=struct;
a = 'Pi';
b = 'e';
mydynvars.(a) = pi;
mydynvars.(b) = exp(1);
mydynvars
mydynvars = struct with fields:
Pi: 3.1416 e: 2.7183

추가 답변 (0개)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by