How to Rename all variables
1 view (last 30 days)
Show older comments
hello,
If a certain if statement is true, i want to rename alle the variables that contains "MAIN_" to "New Name". (All vectors)
Is there an easy way to do this? I tried the rename function but that does not work with double's.
0 Comments
Answers (2)
Guillaume
on 6 May 2015
A variable can't be renamed. All you can do is create a copy of the old one with a new name and then clear the old one:
NewName = Main;
clear Main;
Due to the way matlab works, there won't be any copy actually.
However, there shouldn't be any reason for you to want to rename variables in the first place. If you do, it's most likely because you've been using dynamic variable names, which is a bad idea in the first place
0 Comments
Stephen23
on 6 May 2015
Edited: Stephen23
on 19 Jun 2019
4 Comments
Stephen23
on 6 May 2015
Edited: Stephen23
on 6 May 2015
@Nick van der maat: yes, we know what you are trying to do and that is exactly what we are giving advice about. It is considered to be a bad programming practice generally: variables should not just pop into existence like that. Just because you can do something does not make it a good idea!
If you take the time to read those links then people with more knowledge than me will explain why dynamically creating variables is a bad idea.
John D'Errico
on 6 May 2015
Edited: John D'Errico
on 6 May 2015
@Nick - you are getting good advice from both responders. Please learn from it.
Your code will improve greatly, becoming more robust to bugs. It will be faster to write your code, no longer to need many different variables with all those names. And you can avoid all those otherwise necessary evals, a bad thing in general to use.
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!