Saving a structure element as a .mat file
201 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a set of structures 1.mat , 2.mat and so on.
Each structure has a field as below example:
1.mat.data has a 110 X 116 array
I want to copy 1.mat.data into a separate mat file
The same for the rest of the files.
How can I do it ?
2 commentaires
Rik
le 31 Oct 2022
Your question is a bit confusing. mat files contain variables and can be loaded to a struct. Is that what you mean? So you want to do this?
S=load('1.mat');
data=S.data;
save('new_1.mat',data)
Is that what you mean?
What have you tried already?
Matt J
le 31 Oct 2022
I have a set of structures 1.mat , 2.mat and so on.
Not possible. Those are illegal names for structures, e.g.,
1.mat.data=5
Réponses (1)
Steven Lord
le 31 Oct 2022
If you want to extract some but not all of the variables stored in a MAT-file into a separate file, I'd use load to read just the variables you want to copy over into a struct array then call save with the -struct option. For this example let's work in a temporary directory.
cd(tempdir)
The patients.mat file has a number of variables.
whos -file patients.mat
Let's make a new MAT-file named bloodPressure.mat (I'll add suffixes 1 and 2 to that name to distinguish two approaches) that contains only the Diastolic and Systolic variables from patients.mat. First load those two variables into a struct.
data = load('patients.mat', 'Diastolic', 'Systolic')
Now call save to save that data to a new MAT-file. We could save the data struct array or we could use the -struct option to save each field as a separate variable in the MAT-file.
save('bloodPressure1.mat', 'data') % Storing the struct
whos -file bloodPressure1.mat
save('bloodPressure2.mat', '-struct', 'data') % Storing each field separately
whos -file bloodPressure2.mat
Note that in the case of bloodPressure2.mat the name data doesn't appear in the file anywhere. So if you wanted to do this to a series of files in a for loop you wouldn't have to use a different variable for each loop iteration. Just load the data into the temporary variable which will overwrite the contents from the previous loop iteration.
6 commentaires
Voir également
Catégories
En savoir plus sur Workspace Variables and MAT-Files dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!