Search code examples
performancematlabmatrixfile-writing

Efficiently write matrix to file in custom format in Matlab


Assume we have an N-by-d matrix in Matlab. Let it be

A = rand(N,d);

Also, let D be a cell array of strings, e.g.

D = {'a1', 'a2', ..., 'aN'};

I would like to create a text file, whose i-th line is of the form

D{i} 1:A(i,1) 2:1:A(i,2) ... N:A(i,N)\n

There is a trivial way to do so; open a file for writing and using a double-for loop write each line as follows:

fid = fopen( 'test.txt', 'w' );
for i=1:size(A,1)
   fprintf( fid, '%s', D{i} );
   for j=1:size(A,2)
      fprintf( fid, ' %d:%g', j, A(i,j) );
   end
   fprintf( fid, '\n' );
end
fclose(fid);

This, though, could be extremely slow if N and d are large enough. What I am looking for is an efficient method (if any) that could avoid the using of those for loops. At least one of them.


Solution

  • Taking advantage of how Matlab's fprintf iterates over arrays, the inner for loop can be replaced with:

    fprintf(fid, ' %d:%g', [1:size(A,2);A(i,:)]);
    

    Thus:

    fid = fopen('test.txt', 'w');
    z = 1:size(A,2);
    for i=1:size(A,1)
       fprintf(fid, '%s', D{i});
       fprintf(fid, ' %d:%g', [z;A(i,:)]);
       fprintf(fid, '\n');
    end
    fclose(fid);
    

    You'll need to use a lot more memory to get rid of the outer for loop, which probably wouldn't be a good idea is your A matrix is very large.