Clear Filters
Clear Filters

How to rename an array inside an .mat file?

27 views (last 30 days)
G
G on 6 Nov 2018
Edited: Stephen23 on 6 Nov 2018
I have 8 separate files with an array in each. I am trying to import them but they all have the same array name. How do I change an array name inside a file?

Answers (2)

KSSV
KSSV on 6 Nov 2018
You load the data.....rename it and save into a mat file, if you want it in mat file.
Or if you want it in workspace...load it..and name the variable as you want.
  1 Comment
Stephen23
Stephen23 on 6 Nov 2018
Edited: Stephen23 on 6 Nov 2018
"You load the data.....rename it and save into a mat file, if you want it in mat file."
Note that to do this without magically accessing variable names would require load-ing the .mat file into a structure, creating a new structure using a dynamic fieldname, saving that new structure, then loading the new .mat file...
While this would work, it is a total waste of time: notice how the first step is to load the data. So the data has already been loaded into MATLAB, this means that the entire remaining steps are simply a waste of time (literally: three file operations compared to one). The data can be trivially accessed using the one fieldname (because it is simpler to access the data when the name stays the same).
"Or if you want it in workspace...load it..and name the variable as you want"
As I understand the OP's question, this would probably require magically accessing variable names, which is one way that beginners force themselves into writing slow, complex, buggy code, unless the proposal is to use some verbose method (e.g. switch).

Sign in to comment.


Stephen23
Stephen23 on 6 Nov 2018
Edited: Stephen23 on 6 Nov 2018
"I have 8 separate files with an array in each. I am trying to import them but they all have the same array name. How do I change an array name inside a file?"
Do NOT rename those variables!
When each .mat file has different variable names it makes accessing the data harder.
When each .mat file has the same variable names it makes accessing the data simpler.
Because all of the .mat files contain the same variable name/s you can easily import that data in a loop (the important thing is to load into an output variable, which you should always be doing anyway):
C = cell(1,8)
for k = 1:8
S = load(...) % load into output variable
C{k} = S.fieldname % get the field data
end
And that is all! Notice how the imported name remains exactly the same! Notice how easily the data can be accessed from the cell array C, using very simple and efficient indexing! What you are proposing will be pointlessly complex, and quite likely very slow and buggy too:

Categories

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