Dynamically Naming Variables Saved to A Mat File
Show older comments
Hello,
I am trying to store multiple structures as separate variables in a mat file so that I can then reload these structures separately. I do not want to place them into a cell-array, because then I would have to load the whole cell array at once from the mat file.
The problem is this involves dynamic naming of variables from a nested function, since the variables must have different names.
With this in mind how can I: Store an unknown number of structures in a SINGLE mat file, such that I can load each INDIVIDUALLY without loading the others.
Answers (3)
Fangjun Jiang
on 19 Jun 2011
When you store multiple structures in a SINGLE mat file, you still need to load all the structures in that mat file. When you say "load", do you mean load the mat file, or load the variable. If all the data are in a single mat file, you can't save memory by saving variables in multiple structure, rather than saving in a single structure. For example, you can do:
Str.a=1:10
Str.b=1:100
Str.c=1:1000
or
a=1:10
b=1:100
c=1:1000
You can still reference individual variable in the first scenario:
NewVariable=Str.a
But the first scenario give you much flexibility using the dynamic field name method.
2 Comments
Tomer
on 19 Jun 2011
Fangjun Jiang
on 19 Jun 2011
I see. Then you can run assignin() in your nested function to achieve your goal.
VarName='a';
assignin('base',VarName,1:10);
You got the variable a assigned in the base workspace.
Jan
on 19 Jun 2011
What exactly are "multiple structures"? Saving and loading several STRUCTs is easy:
S1.a = 5;
S1.b = 1;
S2.a = 6;
S2.c = 7;
save('FileName.mat', 'S1', 'S2');
...
Data = load('FileName.mat', 'S1');
This solves your original question "Store an unknown number of structures in a SINGLE mat file".
But do you want to load only "S2.a"? Then I do not see the reason why this variable is stored as field of a STRUCT. Please clarify the wanted inputs and outputs exactly again.
the cyclist
on 19 Jun 2011
0 votes
Usually, people advocate using cell arrays as a way of avoiding the evil "eval()" function. But, if you really need separate variables, eval() may be the way to go.
Categories
Find more on Whos 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!