How to convert a string into a variable?

454 views (last 30 days)
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!

Accepted Answer

Thomas
Thomas on 12 Apr 2012
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 Comment
Jan
Jan on 12 Apr 2012
This creates a valid name, but not a variable itself.

Sign in to comment.

More Answers (2)

Jan
Jan on 12 Apr 2012
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
Edited: Jeferson Araujo de Oliveira on 18 May 2018
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.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!