How to write .xls file to include every output from a for loop?

1 view (last 30 days)
So I have about 50 excel files that I've written a script to loop through to apply several functions, one of which is a polyfit function.
for k=1:length(source_files)
[rows, columns] = size(numData);
year=numData(1:rows,1);
maxt=numData(1:rows,3);
JanMaxT = maxt(1:12:end);
JanYear = year(1:12:end);
idxValid = ~isnan(JanMaxT);
fitJanMaxT = polyfit(JanYear(idxValid),JanMaxT(idxValid),1);
end
now I want to write fitJanMaxT to an excel file which includes all 50 of the polyfit outputs using xlswrite, but when I do I only get the polyfit value of the last of the 50 original files. In other words, the xlswrite function overwrites after each iteration of the for loop. How can I make it so the xlswrite function adds a new row of polyfit data for each input file I have? Also, can I add a column to the newly written xls file that has the names of each of my original 50 files (souce_files)?
Thanks fo the input!!

Accepted Answer

Walter Roberson
Walter Roberson on 20 Mar 2018
Edited: Walter Roberson on 20 Mar 2018
for k=1:length(source_files)
thisfile = source_files{k};
numData = xlsread(thisfile);
[rows, columns] = size(numData);
year=numData(1:rows,1);
maxt=numData(1:rows,3);
JanMaxT = maxt(1:12:end);
JanYear = year(1:12:end);
idxValid = ~isnan(JanMaxT);
fitJanMaxT(k,:) = polyfit(JanYear(idxValid),JanMaxT(idxValid),1);
end
datacell = [source_files(:), num2cell(fitJanMaxT)];
xlswrite('YourOutput.xls', datacell)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!