How can I iterate through an array using a for loop?
Show older comments
I want to iterate through an array of file locations using a for loop.
My current code is something like this:
% Paths where the files are located
P1 = C:\Users\me\Documents\\My Info
%Find excel files in path
%Pull data
% Write into a file
Now this code works great, but now I need to do the same thing to multiple paths while maintaining efficiency. To do this, I created an array of the paths I need to iterate through. How do I use a for loop to iterate through these paths? Here is what I have so far, but my code breaks when it tries to read the path because the text is not scalar when trying to use 'dir'. Here is what I currently have:
% Paths where the files are located
P1 = C:\Users\me\Documents\\My Info
P2 = C:\Users\me\Documents\\My data
%Array of paths
Array = {'P1, P2'}
for i = 1:length(Array)
%Find excel files in path
%Pull data
% Write into a file
Accepted Answer
More Answers (1)
Given an array of paths:
C = {'C:\Users\me\Documents\My Info','C:\Users\me\Documents\My data'};
F = @(p)dir(fullfile(p,'*.xlsx'));
D = cellfun(F,C,'uni',0); % or use a FOR-loop
S = vertcat(D{:}); % comma-separated list
Or assuming a small fixed number of paths:
S = [...
dir('C:\Users\me\Documents\My Info\*.xlsx');...
dir('C:\Users\me\Documents\My data\*.xlsx')];
Then loop over all files (including their paths!):
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
...etc
end
Another option might be to use a datastore:
1 Comment
Sergio E. Obando
on 30 Jul 2024
+1 to using datastore. You should not need to use a for loop if you leverage read/readall and similar to write to file.
Categories
Find more on Loops and Conditional Statements 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!