Borrar filtros
Borrar filtros

How to change a variable name without changing the value itself?

58 visualizaciones (últimos 30 días)
I've got some variables like these: OutArray, OutArray2 and so on...
I need to refresh the base name OutArray adding the "1", "2", "3"... taking advantage of the loop iterator, how may I do it?
I have MATLAB R2023A

Respuesta aceptada

Image Analyst
Image Analyst el 10 de Jun. de 2023
Editada: Image Analyst el 10 de Jun. de 2023
Just do them one at a time, reassiging existing variables to variables with your new, preferred names. Then you can clear the old-named variables from memory with clear if you want.
newname1 = OutArray;
newName2 = OutArray2;
newName3 = OutArray3;
newName4 = OutArray4;
clear('OutArray', 'OutArray2', 'OutArray3', 'OutArray4');
Surely you don't have more than a handful of those variables. If you do (big mistake), then see this
for reasons why not to do that.
If you have tons of variable names because they are columns of a big table you read in from a file, then consider converting them all to a 2-D array with the table2array function.

Más respuestas (4)

Star Strider
Star Strider el 10 de Jun. de 2023
Save them as elements of a cell array instead, when you first create them.

chicken vector
chicken vector el 10 de Jun. de 2023
This is in general not recommend because is prone tu bugs and affects code readibility.
If you really want to do this anyway, have a look at genvarname and eval.

claudio
claudio el 10 de Jun. de 2023
Editada: claudio el 10 de Jun. de 2023
The easy way
variables = ["OutArray" "OutArray2" "OutArray3"];
for kk = 1:numel(variables)
eval(variables(kk) + string(kk) + " = eval(variables(kk))");
clear(variables(kk))
end
A more refined way
variables = string(who); % retrieve the name of the variables from workspace
% without having to write them by hand
for kk = 1:numel(variables)
eval(variables(kk) + string(kk) + " = eval(variables(kk))");
clear(variables(kk))
end
  1 comentario
John D'Errico
John D'Errico el 10 de Jun. de 2023
Editada: John D'Errico el 10 de Jun. de 2023
Neither of those ways is at all refined. And neither of them are a remotely good idea. They will lead to crappy, buggy, and SLOW code, when a simple array was all that was ever needed. Is there even a remotely good reason to recommend this? NO.

Iniciar sesión para comentar.


Antonio Victoria
Antonio Victoria el 13 de Jun. de 2023
Thank you all for your answers!

Categorías

Más información sobre Loops and Conditional Statements 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