필터 지우기
필터 지우기

Running Code On Multiple Files at Once

조회 수: 10 (최근 30일)
RB
RB 2017년 10월 3일
편집: Sharath Chandran 2019년 11월 18일
Hello, I currently have a code that runs on one file: I have a .txt file that is manually loaded into the code as an array (array = load('filename.txt');). Then, the code continues using the specific array that I have manually entered. However, my goal is to get this code to run on an entire folder. I would like to not have to manually enter the file name as the array and instead have to code access a specific folder that contains 100 .txt files and run through the code for each of those files and save the output. The output can either be saved with the addition of '_output' at the end of the filename or keep the same file name and go to a new destination folder (whichever is easiest).
One step further...I am looking to run another code on many more files. For this code, there is a specific folder. Within the folder, there are 100 folders each with 35 .txt files. This code runs on the 35 .txt files and creates an output. However, doing this for all 100 folders takes a long time. Is there a way to have it access the folder, then run the code for each subfolder using the 35 .txt files in each subfolder. The output can be the same as above.
Any help would be greatly appreciated, thank you!

채택된 답변

Sharath Chandran
Sharath Chandran 2017년 10월 12일
편집: Sharath Chandran 2019년 11월 18일
Hi RB,
You could use following piece of code to achieve your objective:
function get_files(folder)
if ~exist(folder, 'dir')
disp('Folder does not exists');
return;
end
files = dir(folder);
for i=3:length(files) % ignore '.' and '..'
file_path = char(strcat(files(i).folder, filesep, files(i).name));
array = load(file_path); %#ok<NASGU>
disp(file_path);
end
end
You can modify the above code to first retrieve all the 100 sub-directories in the folder. Then loop over each sub-dir and call the above function to get names of all the present files to store it in the 'array' variable.
I hope this helps. Let me know if you have any queries or comments on this solution.
Regards,
MathWorks Technical Support.
  댓글 수: 1
Walter Roberson
Walter Roberson 2017년 10월 12일
The above code is not robust and not portable.
function get_files(folder)
if ~exist(folder, 'dir')
disp('Folder does not exists');
return;
end
files = dir(folder);
files([files.isfolder]) = [];
filenames = fullfile(folder, {files.name} );
for K = 1 : length(filenames)
file_path = filenames{K};
array = load(file_path); %#ok<NASGU>
%at this point do something with array
disp(file_path)
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by