Creating a single .mat file by combining several .mat files
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
sai prasanna sai prasanna m s
el 18 de Mayo de 2023
Respondida: David Szwer
el 19 de Mayo de 2023
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 ?
0 comentarios
Respuesta aceptada
David Szwer
el 19 de Mayo de 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
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
save > Save Structure Fields as Individual Variables: https://uk.mathworks.com/help/releases/R2023a/matlab/ref/save.html#mw_f7e7216d-94c3-47ff-a2c6-b68edf25ffa8
Generate Field Names from Variables: https://www.mathworks.com/help/releases/R2023a/matlab/matlab_prog/generate-field-names-from-variables.html
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Variables en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!