Code covered by the BSD License  

Highlights from




04 Feb 2013 (Updated )

simple and elegant matlab function to quickly write large matrices to an ascii file.

function write_ascii(filename,data,delimiter,format)
% 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).
% Inputs:
% 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;
% tic;dlmwrite('test.txt',M,'delimiter','\t','precision','%9.3f');toc;
% tic;write_ascii('test2.txt',M,'\t','%9.3f');toc;
% 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');

Contact us