Rename Matrix in Using String

14 views (last 30 days)
NikkiCalli
NikkiCalli on 4 May 2020
Commented: Adam Danz on 5 May 2020
Hello all,
I would like to rename a matrix based on a string value. I understand there are more sophisticated ways of doing this, but I am just starting out and I am trying not to get too discouraged by very intimidating looking code.
What I have is basically script1 that generates a matrix named outputName . I am using the string filename in multiple places and would like to also use it here also. I am hoping to find a command that would simply change the matrix name in the workspace so it displays NewName instead.
filename='NewName';
rename(outputName,filename) %%% what function can I use here???
My overall goal is to be able to change script1 , import all files in a directory by changing filename, and plot all matrices in my workspace.
  6 Comments
Stephen23
Stephen23 on 5 May 2020
Edited: Stephen23 on 5 May 2020
"I understand there are more sophisticated ways of doing this..."
Actually there are simpler ways of doing this (e.g. indexing, which is also more efficient, less buggy, and easier to debug).
"...but I am just starting out and I am trying not to get too discouraged by very intimidating looking code."
Indexing is simpler than what you are trying to do, and is much more effiicient. If you are just "starting out" with MATLAB, then do yourself a favor and don't shoot yourself in the foot before running in a race.
"My overall goal is to ... import all files in a directory by changing filename, and plot all matrices in my workspace."
So far everything you describe would be trivially achieved using simple, neat, very efficient indexing. Using indexing is not "more sophisticated" than slow and complex dynamic variable names it is simpler and more efficient (both in terms of run-time and your programming time). Indexing is what the MATLAB documentation recommends:
Adam Danz
Adam Danz on 5 May 2020
@NikkiCalli , 50% of the comments/answers in this thread contain the same link warning against the use of dynamic variable naming :D Let us know if you have any troubles reworking an alternative solution.

Sign in to comment.

Answers (1)

James Tursa
James Tursa on 4 May 2020
Edited: James Tursa on 4 May 2020
Suppose you could somehow rename your variable to the name contained in filename. What would you do next? How would you access this variable, under this new name, downstream in your code? You would be forced to write yet more obfuscated code, of course. Don't go down this path. See this link for better options:
You could of course use dynamic field names:
x.(filename) = OutputName;
Now downstream in your code you can use x.(filename)

Categories

Find more on File Operations 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!