dlmwrite vs. writematrix: speed
28 views (last 30 days)
Show older comments
dlmwrite, according to its page, is not recommended. It is suggested to use writematrix instead (better performance). I currently use dlmwrite to continuously append a text file with measurement data. Speed is therefore important. Comparing dlmwrite to writematrix,
fwrtmat = 'test writematrix.txt';
fdlmwrt = 'test dlmwrite.txt';
ncols = 10; % number of columns
niter = 1e3; % number of iterations in test
fmt = ['%f\t\n',repmat('%f\t ', 1, ncols)]; % format for dlmwrite
fmt(end:end+1) = '\n';
fid = fopen(fdlmwrt, 'w');
fclose(fid);
tic
for i = 1:niter
data = rand(1,ncols);
writematrix(data,fwrtmat,'WriteMode','append','FileType','text','Delimiter','tab');
end
toc
tic
for i = 1:niter
data = rand(1,ncols);
dlmwrite(fdlmwrt,data,'-append','delimiter','\t','precision',15); % use same precision as writematrix
end
toc
I found that dlmwrite is faster, which I did not expect. Additionally, the (default?) precision of writematrix is not required and it would even be preferential to sacrifice precision for performance. The file format can be changed if that would improve performance.
Am I using writematrix correctly/optimally in my example? Should I use writematrix or stick to dlmwrite?
0 Comments
Accepted Answer
Sulaymon Eshkabilov
on 17 Mar 2023
If you run this simulation on the MATLAB desktop and shift the orders, their elapsed time will be similar. Anyhow it is interesting :)
Here is another discussion thread demonstrating your conclusion, i.e., dlmwrite() is faster than writematrix(): https://www.mathworks.com/matlabcentral/answers/653363-fastest-way-to-append-file-with-matrix-data
fwrtmat = 'test writematrix.txt';
fdlmwrt = 'test dlmwrite.txt';
ncols = 10; % number of columns
niter = 1e3; % number of iterations in test
fmt = ['%f\t\n',repmat('%f\t ', 1, ncols)]; % format for dlmwrite
fmt(end:end+1) = '\n';
fid = fopen(fdlmwrt, 'w');
fclose(fid);
tic
for i = 1:niter
data = rand(1,ncols);
dlmwrite(fdlmwrt,data,'-append','Delimiter','\t','precision',15); % use same precision as writematrix
end
TDLM=toc
tic
for i = 1:niter
data = rand(1,ncols);
writematrix(data,fwrtmat,'WriteMode','append','FileType','text','Delimiter','\t');
end
TWRTM=toc
More Answers (0)
See Also
Categories
Find more on Text Files 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!