How can I define a variable with a name based on an input?
68 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I want my script to create new variables whose names depend on an input, e.g.:
ship_name = input('Name of the ship: ','s');
[the string, ship_name, here]_name = ship_name %#ok<NOPTS>
I know I want the latter half of this second variable to be '_name', but how do I get the former half to be identical to the string input by the user, so this happens in the command window:
Name of the ship: Orange
Orange_name =
"Orange"
Over time, many different ships exist, such that there may be an Orange_name, a Green_name, and a Blue_name. My script will later know which ship it's working with:
ship_current = input('Which ship are you working with? ');
And I want it to return the string called Orange_name when ship_current = "Orange", the string called Green when ship_current = "Green", and so forth. This may seem useless, but there will also be ship_mass and ship_capacity variables, so the script will basically remember the details of each ship until they're needed later. I also think I can achieve the same thing by concatenating onto a cell containing this information, but I had this variable name idea and wanted to know if it was feasible to do this, regardless of how unnecessarily difficult it may be.
3 commentaires
Paolo
le 14 Août 2018
Very good advice Stephen. Sometimes I just focus on answering the question without seeing the bigger picture, I guess that comes with experience :)
Réponse acceptée
Paolo
le 13 Août 2018
If I am understanding your question correctly, you can use:
ship_name = input('Name of the ship: ','s');
assignin('base',strcat(ship_name,'_name'),ship_name);
Will create a variable named such as Orange_name with value Orange.
3 commentaires
Paolo
le 13 Août 2018
Modifié(e) : Paolo
le 13 Août 2018
You are welcome, happy to help.
The usage of the base or caller options depends as to whether you are calling the assignin function from a script or a function (if called by another function).
For a script, use base.
For a function ( let's call it callee ), you use caller to assign the variable to the workspace of the function that called callee.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing 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!