Rename Matrix in Using String

16 visualizzazioni (ultimi 30 giorni)
NikkiCalli
NikkiCalli il 4 Mag 2020
Commentato: Adam Danz il 5 Mag 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 Commenti
Stephen23
Stephen23 il 5 Mag 2020
Modificato: Stephen23 il 5 Mag 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 il 5 Mag 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.

Accedi per commentare.

Risposte (1)

James Tursa
James Tursa il 4 Mag 2020
Modificato: James Tursa il 4 Mag 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)

Categorie

Scopri di più su File Operations in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by