04 Feb 2013
03 Sep 2013)
simple and elegant matlab function to quickly write large matrices to an ascii file.
% Writes large matrices to an ascii file. Format is up to user. Function
% automatically appends to file. It is many times (10-20X) faster than dlmwrite
% and almost as fast as using a mex file. Uses sprintf and fwrite (opposed to fprintf).
% filename: output filename absolute or relative
% data: matrix to output
% format: spacing and precision format to write to (defaults to 9.3f)
% delimiter: delimiter for writing (defaults to tab)
% Example usage:
% M = rand(1e5,3)*1000;
% Elapsed time is 7.446049 seconds.
% Elapsed time is 0.513611 seconds.
if nargin<4, format = '%9.3f';end
if nargin<3, delimiter = '\t';end
nCols = size(data,2);
% format as string
data = sprintf([format delimiter],data')';
% convert to ascii numbers
data = uint8(data);
% add line feeds at end of each row
delLocations = find(data==double(sprintf(delimiter)));
feedLocations = delLocations(nCols:nCols:end);
data(feedLocations) = 10;
% write/append to file (at means carraige return is added in write)
fid = fopen(filename,'at');