Load, Process, Rename and Save Multiple Files
Ältere Kommentare anzeigen
Dear Matlabers,
I know in the Matlab FAQ there's a very popular solution to how to load multiple files, but it doesn't help me, as I can't convert it into my specific problem.
I have files named file1.mat, file2.mat and file3.mat. I want to load the files into matlab, then multiple each file by a number and save them with as filenames fileprocessed1.mat, fileprocessed2.mat and fileprocessed3.mat respectively.
Thanks so much for your help and have a nice day.
2 Kommentare
a .mat file is a file that can contain any kind and number of variables, including strings, objects, function handles, structures, cell arrays, etc.
What does "multiplying a file by a number" mean in that contest?
Is it all the variables in each .mat file that you want to multiply? Do the variables have the same names in the each file?
AT
am 18 Mai 2016
Antworten (1)
Guillaume
am 18 Mai 2016
folder = 'c:\somewhere\somefolder';
numfiles = 100;
multiplier = 5;
for fileidx = 1:numfiles
oldcontent = load(fullfile(folder, sprintf('file%d.mat', fileidx));
newcontent = structfun(@(m) m * multiplier, oldcontent);
save(fullfile(folder, sprintf('fileprocessed%d.mat', fileidx)), '-struct', 'newcontent');
end
is one way to do it. Instead of generating the names of the file to read you can also obtain them with dir if you prefer.
Because load is assigned to a variable, the original variables of the .mat file are transformed into fields of the oldcontent structure. I use structfun to multiply each field of the structure by your constant and create a new structure with the same field names. save with the '-struct' option then save the fields of the structure back as variables.
4 Kommentare
AT
am 18 Mai 2016
Guillaume
am 18 Mai 2016
If you type
doc fullfile
or Press F1 with your cursor on the word, you get its documentation which explains what it does: "Build full file name from parts". Basically, it builds the path of the file, without you having to worry about the directory separator (/ on linux, \ windows).
AT
am 19 Mai 2016
Spend some time understand the code I've written. You're free to change the values that are passed to the loop (or as I've said you could obtain the list of files with dir as per the examples you said you've read).
In your case, this simple change should solve the problem:
for fileidx = [26 27 29 30]
Kategorien
Mehr zu Whos finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!