For a big matrix, how to accelerate fprintf?
Show older comments
Hello everyone, I have a 2500*1500 matrix and I want to print every column to a txt file, 5 numbers every row. Using :
for i=1:1500,
fprintf(fid, 'This is the %d coefficients\n', i);
S=sprintf(' %15.8E %15.8E %15.8E %15.8E %15.8E\n', coeff(:, i));
S(S=='E')='D';
fprintf(fid, '%s', S);
end
it will take several seconds. I'd like to know how can I accelerate this?
3 Comments
Walter Roberson
on 10 Jan 2017
Would it be okay to put 'This is the %d coefficients' on a separate line? Currently it is on the same line as the first line of data for the column.
Your changing to 'D' suggests that you might be reading this in fortran. But the 'This is' string makes it clearly a custom format, so it does not appear that you need compatibility with some other program. Have you considered writing in binary?
Accepted Answer
More Answers (1)
Jan
on 10 Jan 2017
This could be slightly faster:
fid = fopen(FileName, 'W'); % Uppercase W for better buffering
if fid == -1
error('Cannot open file for writing: %s', FileName);
end
for i = 1:1500,
fprintf(fid, 'This is the %d coefficients\n', i);
S = sprintf(' %15.8E %15.8E %15.8E %15.8E %15.8E\n', coeff(:, i));
fwrite(fid, strrep(S, 'E', 'D'), 'char');
end
But I assume the bottleneck is the slow disk transfer. The 'W' can reduce this, using an SSD would be better.
2 Comments
Tian
on 11 Jan 2017
Scott Campbell
on 7 Dec 2022
My 15 Mb csv file went from 30 to 10 seconds.
Categories
Find more on Tables 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!