Variables under the same name in different .mat files

29 views (last 30 days)
I have 11 different .mat files saved that contain the same variables. The variables have the same name and i want to create a .mat file that contains all of those variables separately. For example, say the .mat file name is FILE1.mat and contains variable A and then i have FILE2.mat that contains variable A but with different content. I want to create FILE.mat with variables A1 (From FILE1) and A2 (from FILE2). Any ideas?
  1 Comment
Stephen23
Stephen23 on 7 Aug 2020
Forcing numbers into variable names is a sign that you are doing something wrong.
Instead of making your data harder to access, you should just use one simple non-scalar structure. Then you can trivially and efficiently access your data using basic indexing:

Sign in to comment.

Answers (2)

Star Strider
Star Strider on 7 Aug 2020
Use load to load each of the files into a different structure. See Load List of Variables into Structure Array.
You can then identify and rename the variables to save as different variables in the new .mat file.

Stephen23
Stephen23 on 7 Aug 2020
Edited: Stephen23 on 7 Aug 2020
Rather than loading into separate structures and creating numbered variables (which is a bad way to write code), you should simply load the data and create one structure array which you can trivially accessing using basic indexing:
N = number of files
C = cell(1,N);
for k = 1:N
C{k} = load(...,'A');
end
S = [C{:}]; % create structure array
Then you can simply and efficiently access its data:
S(1).A
S(2).A
S(3).A
...
and of course saving it is easy too:
save('myfile.mat','S')

Community Treasure Hunt

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

Start Hunting!