Effacer les filtres
Effacer les filtres

How to convert a string into a variable?

450 vues (au cours des 30 derniers jours)
osminbas
osminbas le 12 Avr 2012
Commenté : Stephen23 le 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!

Réponse acceptée

Thomas
Thomas le 12 Avr 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 commentaire
Jan
Jan le 12 Avr 2012
This creates a valid name, but not a variable itself.

Connectez-vous pour commenter.

Plus de réponses (2)

Jan
Jan le 12 Avr 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
Modifié(e) : Jeferson Araujo de Oliveira le 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.

Catégories

En savoir plus sur Argument Definitions dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by