Assigning input string as variable name
Mostra commenti meno recenti
Hi everyone, I have a quick question. I would like to ask the user to input the name of a variable and then use that string as a new variable name. For example, say I have the value [0 1 2 3 4]. I want to ask the user to give the name he would like to that variable.
So, for example:
x = input('Enter the name of the new variable: ') Say the user enters: new_var
I want:
new_var = [0 1 2 3 4]
Can someone explain how to do this?
Thanks for the help
Risposta accettata
Più risposte (3)
Andrei Bobrov
il 4 Lug 2012
Modificato: Andrei Bobrov
il 4 Lug 2012
x = input('Enter the name of the new variable: ','s');
eval([x,'=0:4;']);
Arash Roozitalab
il 18 Apr 2018
Hello. One might use
assignin('base',var_name, value)
to assign a
value
to a string
var_name = "given_name"
1 Commento
Note that assignin suffers from all of the same problems as eval does: slow, complex, obfuscated code, buggy, and hard to debug. This does not depend on which command is used, but these problems are caused by the act of magically assigning values to variable names dynamically. See:
Beginners wanting to learn how to write neat, efficient MATLAB code that is easy to debug should focus on keeping their data in as few arrays as possible, and use indexing to access it. As has already been discussed many times on this forum, they should avoid using eval, assignin, etc.
Categorie
Scopri di più su Variables in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!