Creating a single .mat file by combining several .mat files

4 views (last 30 days)
Hi,
I have x number of .mat files that are structured in the same way.
Each .mat file has a variable named mydata.
I want to generate a fresh.mat file, such that the variable mydata of each file is stored in the name of its parent .mat file.
For example:
1.mat contains mydata
2.mat contains mydata
...
x.mat contains mydata
The new file, fresh.mat must contain variables named as 1 2 3 .. x
How can I do this ?

Accepted Answer

David Szwer
David Szwer on 19 May 2023
This can be done with structures. Here's a demonstration - only the middle cell is the code you actually need.
%% Set up the demonstration.
mydata = "1"; save("mat1.mat", "mydata");
mydata = "2"; save("mat2.mat", "mydata");
mydata = "3"; save("mat3.mat", "mydata");
mydata = "Thew, thew, thew!"; save("matthew.mat", "mydata");
% Note that if your files are really just called "1.mat" etc., this won't work; no
% Matlab variable can have a name that starts with a number.
%% The solution
% List your file names here, without path or extension.
filenames = ["mat1" "mat2" "mat3" "matthew"];
for filename = filenames
% The command:
% S = load(filename + ".mat");
% creates a structure "S" whose fields are the variables in the .mat file. For
% you, that's just "mydata", so you would end up with a structure "S.mydata".
% Instead, lets put it in a sub-structure named after the file name.
%
% Add the full path to the load() command if you need to.
structFromMatFile.(filename) = load(filename + ".mat");
% Remove your data from the field called "mydata", and put it directly in the
% field named after the file name.
structFromMatFile.(filename) = structFromMatFile.(filename).mydata;
end
% The save() function has an option that saves every field in a structure into a
% .mat file, as separate variables named after the field.
save("fresh.mat", "-struct","structFromMatFile")
%% Show that all the data were saved.
clear("variables")
load("fresh.mat")
whos
Name Size Bytes Class Attributes mat1 1x1 150 string mat2 1x1 150 string mat3 1x1 150 string matthew 1x1 170 string
Relevant help pages are:
load > Load List of Variables into Structure Array: https://uk.mathworks.com/help/releases/R2023a/matlab/ref/load.html#btm3ohm-1

More Answers (0)

Categories

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