How to convert a string into a variable?

450 次查看(过去 30 天)
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..

更多回答(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
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