Read multiple xls files in a for loop
2 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
採用された回答
Jan
2013 年 7 月 4 日
Please use the debugger to find out more details:
dbstop if error
Then run the program until it stops and check:
size(datestr(d, 2))
size(ds)
Do the number of elements match?
4 件のコメント
Jan
2013 年 7 月 10 日
Now we see, that there is an error in the "line 29: n=length(data)", but what is the error message? And This line does not occur in the posted code.
It is not useful to declare the variable used as a loop counter before:
%Omit this: i=n; % defines variable 'i' for for loop
for i = 1:n
...
Inside the loop, i goes from 1 to n, so you do not have to check "if i <= n".
その他の回答 (1 件)
Evan
2013 年 7 月 3 日
編集済み: Evan
2013 年 7 月 3 日
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 件のコメント
Evan
2013 年 7 月 3 日
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?
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!