Load, Process, Rename and Save Multiple Files
이전 댓글 표시
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
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
2016년 5월 18일
답변 (1개)
Guillaume
2016년 5월 18일
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
AT
2016년 5월 18일
Guillaume
2016년 5월 18일
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
2016년 5월 19일
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]
카테고리
도움말 센터 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!