Create variable with name from other variable string

Hello,
My question is, if i have a string variable, coulf i assing that string as a name for a new variable?
For example, if i have
name_string = 'name_var';
can i have
name_var = 5;
somehow wihouth me writing the actual code?

 Respuesta aceptada

While it is not adviseable to have variables created in this way maybe you have a good reason to but still un-adviseable but here you go:
name_str = 'name_var';
eval(sprintf('%s = 5',name_str))
name_var = 5
disp([name_str 'has been assigned to ' num2str(name_var)])
name_varhas been assigned to 5

3 comentarios

Stephen23
Stephen23 el 26 de Jun. de 2021
Editada: Stephen23 el 26 de Jun. de 2021
"...maybe you have a good reason..."
It is rather curious, that almost every time I ask for that specific "good reason" that some beginner insists that they have that requires them to dynamically name variables, either of these happen:
  1. it turns out that their data and/or code is very poorly designed (and someone shows them significantly improved code using simpler, more robust, much more efficient design concepts).
  2. they disappear from this forum without actually describing the specific "good reason" (or they just keep repeating "I must do this", without explaining why).
For the sake of my own curiosity, what is this mystery "good reason" ?
Hello!! Thank you very much for the answer,
Of course I can give the simplified context,
I have an excel file with some names and some related number codes, i will read the excel list and do some math operations with the code and then generate a "NAME_CODE.mat" file so i can email each pearson their files, no one can have access to another person file.
Stephen23
Stephen23 el 28 de Jun. de 2021
Editada: Stephen23 el 28 de Jun. de 2021
@Victor Andrés Sánchez Zurita: nothing in your description requires dynamically named variables.
Most likely this is a complex and inefficient approach to processing your data.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Variables en Centro de ayuda y File Exchange.

Productos

Versión

R2020b

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by