Read multiple xls files in a for loop
Show older comments
Hello! I was trying to get 3 excel files to read through a for loop and do a simple function. The dates (mm/dd/yy) read into matlab code and I'd like to spit them back out as new variables that translate them back into dates via the datestr function. I know its my coding that is the problem and I've tried manipulating it several times with no success so any suggestions would be greatly appreciated! Thanks!
source_dir = '/Users/student/Documents/MATLAB/RAWS Station Data';
dest_dir = '/Users/student/Documents/MATLAB/RAWS Results';
source_files = dir(fullfile(source_dir, '*.xls'));
n=length(source_files);
i=n;
for i=1:n
a= xlsread(source_files);
d = a(:,1);
ds(i) = datestr(d,2);
end
Accepted Answer
More Answers (1)
Is this any better?
source_dir = '/Users/student/Documents/MATLAB/RAWS Station Data';
dest_dir = '/Users/student/Documents/MATLAB/RAWS Results';
source_files = dir(fullfile(source_dir, '*.xls'));
n=length(source_files);
for i=1:n
a = xlsread(source_files(i).name);
d = a(:,1);
ds(i) = datestr(d,2);
end
Your problem looks to be caused by the fact that source_files is an nx1 struct, where n is the number of .xlsx files in your directory. To read in each .xlsx file one at a time, you have to loop through that struct, accessing its "name" field in your call to xlsread.
5 Comments
Theodore
on 3 Jul 2013
Evan
on 3 Jul 2013
Yep, any time you have a structure and you want to loop through it, you use syntax like a did above.
Also, try this for ds:
ds(i,:) = datestr(d,2);
Theodore
on 3 Jul 2013
Evan
on 3 Jul 2013
Hmmm. Interesting. Just out of curiosity, is this a script or a function? If it's just a script, are you calling clear before running again?
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!