Filter löschen
Filter löschen

How to convert a string into a variable?

450 Ansichten (letzte 30 Tage)
osminbas
osminbas am 12 Apr. 2012
Kommentiert: Stephen23 am 18 Mai 2018
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!

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Jan
Jan am 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
Bearbeitet: Jeferson Araujo de Oliveira am 18 Mai 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.

Kategorien

Mehr zu Argument Definitions finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by