Effacer les filtres
Effacer les filtres

Running Code On Multiple Files at Once

10 vues (au cours des 30 derniers jours)
RB
RB le 3 Oct 2017
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!

Réponse acceptée

Sharath Chandran
Sharath Chandran le 12 Oct 2017
Modifié(e) : Sharath Chandran le 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 commentaire
Walter Roberson
Walter Roberson le 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by