Running Code On Multiple Files at Once

43 views (last 30 days)
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!

Accepted Answer

Sharath Chandran
Sharath Chandran on 12 Oct 2017
Edited: Sharath Chandran on 18 Nov 2019
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 Comment
Walter Roberson
Walter Roberson on 12 Oct 2017
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

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!