简体   繁体   English

在Matlab中将2d矩阵导出为三元组格式CSV文件的最快方法

[英]Fastest way to export a 2d matrix to a triples format CSV file in Matlab

I want to convert a 2d matrix, for example: 我想转换2d矩阵,例如:

10  2
3   5

to a (row,col,value) CSV file, for example: 到(row,col,value)CSV文件,例如:

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

is it possible to do it in a single Matlab command? 是否可以在单个Matlab命令中执行此操作?

I didn't find a way with a single command, but try the following code: 我没有找到使用单个命令的方法,但请尝试以下代码:

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

The output is: 输出是:

type test.csv

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

Assuming A to be the input matrix, two approaches can be suggested here. 假设A是输入矩阵,这里可以建议两种方法。

fprintf based solution - 基于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 based approach - 基于dlmwrite的方法 -

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

Some quick tests seem to suggest that fprintf performs better across varying input datasizes. 一些快速测试似乎表明fprintf在不同的输入数据量上表现更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM