How do you set a variable name to a variable value?

34 vues (au cours des 30 derniers jours)
JIWON LEE
JIWON LEE le 6 Août 2021
Commenté : Stephen23 le 6 Août 2021
If I make a variable ( a = 'name' ), I want to set the variable name with the value of a.
ex) ( name = )
  4 commentaires
KSSV
KSSV le 6 Août 2021
John = 3 ;
This is enough right.
Stephen23
Stephen23 le 6 Août 2021
Before you force yourself into writing slow, inefficient, complex code that is difficult to debug, you should read this:

Connectez-vous pour commenter.

Réponse acceptée

Dave B
Dave B le 6 Août 2021
Modifié(e) : Dave B le 6 Août 2021
You can do this with eval, but you are likely to regret this.
a = 'Pi';
val = pi;
eval(a + " = " + val);
Pi = 3.1416
This link has some alternatives to using string evaluation to run code. It's a bad/dangerous style and there's almost always a better approach.
If you must name your variables with another variable, consider using fields of a struct rather than raw variables:
mydynvars=struct;
a = 'Pi';
b = 'e';
mydynvars.(a) = pi;
mydynvars.(b) = exp(1);
mydynvars
mydynvars = struct with fields:
Pi: 3.1416 e: 2.7183

Plus de réponses (0)

Catégories

En savoir plus sur Variables dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by