Fastest way to export 2d matrix to CSV file with triplets in Matlab

I want to convert a 2d matrix, for example:

10  2
3   5

      

to CSV file (string, col, value) like:

1,1,10
1,2,2
2,1,3
2,2,5

      

is it possible to do this in one Matlab command?

+3


source to share


2 answers


I haven't found a single command method, but I'll try the following code:

[i1,i2] = ind2sub(size(A),1:numel(A));
csvwrite('test.csv',[i2',i1',reshape(A',numel(A),1)]);

      



Output:

type test.csv

1,1,10
1,2,2
2,1,3
2,2,5

      

+2


source


Assuming which A

is the input matrix, two approaches can be suggested here.

fprintf

-

output_file = 'data.txt'; %// Edit if needed to be saved to a different path
At = A.';  %//'
[y,x] = ndgrid(1:size(At,1),1:size(At,2));
fid = fopen(output_file, 'w+');
for ii=1:numel(At)
    fprintf(fid, '%d,%d,%d\n',x(ii),y(ii),At(ii));
end
fclose(fid);

      




dlmwrite

-

At = A.';  %//'
[y,x] = ndgrid(1:size(At,1),1:size(At,2));
dlmwrite(output_file,[x(:) y(:) At(:)]);

      

Some quick tests show fprintf

it performs better on various inputs.

+2


source







All Articles