Help Creating For Loop to Run Functions on Multiple Files
古いコメントを表示
I wrote a function that I want to apply to every file in a folder. I found this resource (https://www.mathworks.com/matlabcentral/answers/1445389-applying-a-single-function-to-many-files-in-one-folder) for creating a loop to apply my function to the files in a folder. The code shared is as follows:
FolderIn = 'D:\Your\Folder'; FolderOut = 'D:\Your\B' FileList = dir(fullfile(Folder, '*.mat’)); for iFile = 1:numel(FileList) File = fullfile(Folder, FileList(iFile).name); Data = load(File); % Now do what you want with the data NewData = Data; save(fullfile(FolderOut, FileList(iFile).name), 'NewData', '-struct'); end
1. I don’t understand what “ D: ” does in their code. In the first two lines. 2. Even when I set the directory to the folder containing the files I want to reference, the “fullfile” function does not run when I give it the file name. 3. Is there a better way to run my function on a bunch of files?
Thank you!
3 件のコメント
"I don’t understand what “ D: ” does in their code"
D is the drive letter, usually corresponding to a hard-drive or SSD: https://en.wikipedia.org/wiki/Drive_letter_assignment
"Even when I set the directory to the folder containing the files I want to reference, the “fullfile” function does not run when I give it the file name"
The variable FOLDER is not defined. That code will not work until it is defined or changed to another variable.
You also need to make sure that the DIR match string matches your files. Currently it matches .MAT files: do you have .MAT files?
"Is there a better way to run my function on a bunch of files?"
DIR is a good approach if you need to process files in a loop.
COPYFILE is probably a simpler approach to copying MAT files from one folder to another:
it can even copy multiple files at once.
Kristine
2025 年 3 月 21 日
Stephen23
2025 年 3 月 21 日
"What does DIR stand for..."
This function: https://www.mathworks.com/help/matlab/ref/dir.html
"... and what is a DIR match string in layman's terms?"
FileList = dir(fullfile(Folder, '*.mat’));
% ^^^^^^^^^^^^^^^^^^^^^^^^^ this
The match string (simply called "name" in the DIR documentation) has to match the filenames (possibly including paths) of the files that you wish DIR to identify.
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で File Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!