필터 지우기
필터 지우기

How to convert a string into a variable?

조회 수: 450 (최근 30일)
osminbas
osminbas 2012년 4월 12일
댓글: Stephen23 2018년 5월 18일
Hello,
I have a variable (vector) defined at the beginning of my code, say A1. Then I define string:
Name=strcat('A','1');
Now Name='A1'. How can I convert it into a variable? It might not make sense to define a string with a variable and try to convert it to the variable itself but it will be helpful in my code. Thank you!

채택된 답변

Thomas
Thomas 2012년 4월 12일
doc genvarname
'eval' can do it however...
'EVAL' is very dangerous to use and is very hard to debug..
Here are some techniques given by Walter in reply 2 that explain what you can do, and what you should not do..
  댓글 수: 1
Jan
Jan 2012년 4월 12일
This creates a valid name, but not a variable itself.

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

추가 답변 (2개)

Jan
Jan 2012년 4월 12일
The eval command can do this:
A1 = 23;
Name = 'A1';
disp(eval(Name));
But this is inefficient and prone to bugs, which are extremly hard to find. Therefore it is strongly recommended to avoid such dynamic variable access, see: FAQ: How to create variables A1, A2, ... in a loop.
You find a bunch of posts related to the avoidance of eval in this forum. There is always a better solution.

Jeferson Araujo de Oliveira
Jeferson Araujo de Oliveira 2018년 5월 18일
편집: Jeferson Araujo de Oliveira 2018년 5월 18일
I second the comments from the other developers: there's always a way to avoid creating variable names dynamically. 'eval' is the command that allows you to do it, but maybe containers.Map could be a better solution: https://uk.mathworks.com/help/matlab/ref/containers.map.html;jsessionid=3832da8c651c2187ef12c4505fcb
Anyway, I've had issues with genvarname dealing with special characters in the past. This is more robust:
varName = matlab.lang.makeValidName('123your.string(1)')
PS: this will only modify your string so that it becomes a valid variable name, if it isn't already.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by