MATLAB Answers

Create variable with name from other variable string

조회 수: 5(최근 30일)
Victor Andrés Sánchez Zurita
Victor Andrés Sánchez Zurita 2021년 6월 26일
편집: Stephen 2021년 6월 28일
My question is, if i have a string variable, coulf i assing that string as a name for a new variable?
For example, if i have
name_string = 'name_var';
can i have
name_var = 5;
somehow wihouth me writing the actual code?

채택된 답변

Joseph Cheng
Joseph Cheng 2021년 6월 26일
While it is not adviseable to have variables created in this way maybe you have a good reason to but still un-adviseable but here you go:
name_str = 'name_var';
eval(sprintf('%s = 5',name_str))
name_var = 5
disp([name_str 'has been assigned to ' num2str(name_var)])
name_varhas been assigned to 5
  댓글 수: 3
Stephen 2021년 6월 28일
@Victor Andrés Sánchez Zurita: nothing in your description requires dynamically named variables.
Most likely this is a complex and inefficient approach to processing your data.

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

추가 답변(0개)




Community Treasure Hunt

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

Start Hunting!

Translated by