How to write a Loop to run a specific code to every table in a cell
Show older comments
I have many excel files (540 files) which I used this code to import them to Matlab:
D = 'C:\Users\Behzad\Desktop\New folder (2)';
filePattern = fullfile(D, '*.xlsx');
file = dir(filePattern);
x={};
for k = 1 : numel(file)
baseFileName = file(k).name;
fullFileName = fullfile(D, baseFileName)
x{k} = readtable(fullFileName);
fprintf('read file %s\n', fullFileName);
end
After doing that x is a 1*540 cell which contains 540 tables. I want to apply this code below for all these tables:
T = readtable(filename);
sort = sortrows(T, 8);
selected_table = sort (:, 8:9);
dt1 = datetime([1982 01 01]);
dt2 = datetime([2018 12 31]);
allDates = (dt1 : calmonths(1) : dt2).';
allDates.Format = 'MM/dd/yyyy';
tempTable = table(allDates(~ismember(allDates,selected_table.data)), NaN(sum(~ismember(allDates,selected_table.data)),size(selected_table,2)-1),'VariableNames',selected_table.Properties.VariableNames);
T2 = outerjoin(sort,tempTable,'MergeKeys', 1);
T2 = fillmissing(T2, 'next', 'DataVariables', {'lat', 'lon', 'station_elevation'})
I don't know how to do that. I guess I should use the loop again but haven't any idea how to do it.
Best Regards
2 Comments
Adam Danz
on 20 Dec 2019
Edited: per isakson
on 22 Dec 2019
The for-loop wouldn't be too much different from your first for-loop. What part are you stuck on?
BN
on 20 Dec 2019
Accepted Answer
More Answers (2)
D='C:\Users\Behzad\Desktop\New folder (2)';
d=dir(fullfile(D, '*.xlsx'));
for i=1:numel(d)
tt=readtable(fullfile(d(i).folder,d(i).name)); % read file as table
tt=table2timetable(tt,'RowTimes',tt.data); % convert to timetable ('data' is typo for 'date'???)
tt.data=[]; % get rid of the now unneeded date column
[~,isrt]=sort(tt.Time); % sorted row index with which to...
tt=tt(isrt,:); % sort by increasing time
tt.region_id=categorical(tt.region_id); % I'd do this with all these type variables, just example how
tt=retime(tt,'monthly'); % put on monthly basis, create any missing
tt=fillmissing(tt,'next','datavariables',{'lat','lon','station_elevation'}); % fill in missing
isn=isnan(tt.tm_m); % find missing mean temperatures
tt.tm_m(isn)=mean([tt.tmax_m(isn) tt.tmin_m(isn)],2); % fill in with average min/max (presumes they're not nan, too)
end
Above does all you asked for each file; do what is needed like writetable or save or whatever at the end of the loop before going on and overwriting the previous.
No second loop required for any operations; read the Matlab examples carefully and see how vectorized functions work...it's the key to effective use of Matlab.
2 Comments
BN
on 22 Dec 2019
Have to see the code exactly as you ran it and the specific error in context...it ran on sample file here.
If the optional second argument to the mean() function were missing that would explain the error, though; it would average the columns to two values instead of the rows to the number of missing elements.
NB: Your fillmissing will NOT fill in anything for the temperatures for the missing dates so there will be NaN average temperatures at those locations. That may well be desired; just noting.
Image Analyst
on 21 Dec 2019
1 vote
I'd build your second snippet of code into a function and then call that inside the loop of your first snippet.
Categories
Find more on Timetables 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!