Is it possible to transform a string to a variable code name in MATLAB?

122 visualizaciones (últimos 30 días)
Brando Miranda
Brando Miranda el 21 de Mzo. de 2016
Comentada: Stephen23 el 30 de Abr. de 2019
This might be a very bizarre question (and probably I might be advised against doing such a weird thing) but if I have a string as in `v_str ='var_name'` and I want to transform the contents of that code into the actual code, is that possible in MATLAB? As in:
v_str = 'var_name'
x = make_string_to_code(v_str)
translates to the functioning code:
x = var_name
which simply transforms the string to actual code.
The only way I thought of doing this is by writing a file with that code and then on the next line executing that fine, but I wanted to avoid writing files every time that I want to do this
  3 comentarios

Iniciar sesión para comentar.

Respuestas (2)

Adam el 21 de Mzo. de 2016
Editada: Adam el 21 de Mzo. de 2016
You are correct that this is something you will be strongly advised against even trying to do. Someone will probably post a relevant set of links to places that tell you why not, but as to an alternative solution, use a struct and a dynamic string to access its fields if you want to do something like this. e.g.
myStruct.var_name = 6;
v_str = 'var_name';
x = myStruct.( v_str );
would be equivalent to just
x = 6;
This can be especially useful if you are loading data from a mat file since the 'load' function allows you to load all the variables into the workspace as fields of a struct rather than just depositing them all into the workspace.

Renato Agurto
Renato Agurto el 21 de Mzo. de 2016
Editada: Renato Agurto el 22 de Mzo. de 2016
x = eval(v_str);
It is normal to advice against it, but normally when the left side of the equation is a string
  1 comentario
Stephen23 el 22 de Mzo. de 2016
"It is normal to advice against it"
"but normally when the left side of the equation is a string"
It is advised to avoid eval in all cases, both on the LHS and RHS. In all cases it is a buggy, obfuscated, and slow way to code. It does not matter that "side" it is on, using eval will always be buggier and slower than calling functions directly or using proper data structures.

Iniciar sesión para comentar.


Más información sobre Search Path en Help Center y File Exchange.


Community Treasure Hunt

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

Start Hunting!

Translated by