Why xlswrite slow down in a for loop?
Show older comments
Hello,
when I use xlswrite in a for loop, the time spend by xlswrite increases at each loop. The following code is an illustration of the problem. Thanks in advance if somebody knows a solution to fix the problem
if true
clear all
close all
Nb=500;
Time=zeros(Nb,1)+nan;
filename = 'testdata.xlsx';
sheet = 'MySheet';
xlRange = 'E1';
t1=tic;
for i=1:Nb
t0=tic;
A = {'Time','Temperature'; rand,rand; rand,rand; rand,rand};
xlswrite(filename,A,sheet,xlRange)
Time(i)=toc(t0);
end
toc(t1)
figure
plot(Time(2:end))
grid on
end
Answers (1)
Walter Roberson
on 3 Sep 2018
0 votes
Xlsx files are zipped structures of text files. Each time you xlswrite it has to parse the existing text, make the appropriate binary adjustments, and write it all out and zip again.
Writing incrementally to spreadsheets is not recommended.
You must be using Windows or else you would have received an error message when you tried to write nonnumeric values with xlswrite. Consider instead using ActiveX to talk to excel to make the updates. Or better yet, accumulate all of the data and write it at the end.
3 Comments
Image Analyst
on 3 Sep 2018
I'm kind of surprised this slows it down because I think that starting a few versions ago they switched from launching Excel every time (which would be very slow) to using ActiveX and leaving the server running, which is much, much faster. I think Tibo must be using a version several years old.
Walter Roberson
on 3 Sep 2018
No it seems to be marked as r2018a
Tibo
on 4 Sep 2018
Categories
Find more on Data Import from MATLAB 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!