如何通过从Matlab数组中删除零来创建CSV文件

时间:2015-01-27 16:18:31

标签: matlab file csv

我有一个Matlab数组: A = [1 2 0 0 0; 7 8 9 1 2; 4 5 6 0 0]

我需要按以下格式将此数组写入CSV文件: 1 2 \ n 7 8 9 1 2 \ n 4 5 6

这意味着我需要在编写CSV文件时删除零。除了dlmwrite()之外是否还有其他函数可以通过删除零来创建这样的CSV文件?

3 个答案:

答案 0 :(得分:1)

使用fprintf -

的一种方法
output_file = 'results.txt';    %// output text filename
fid = fopen(output_file, 'w');  %// open file for writing
for k = 1:size(A,1)             %// run for-loop for all rows

    %// For each row select the non zero elements and then create a 
    %// non-trailing string version of it and write to each line of output file
    fprintf(fid, '%s\n',num2str(nonzeros(A(k,:))')); %//'
end
fclose(fid);                    %// close the file after writing

验证 -

>> type results.txt

1  2
7  8  9  1  2
4  5  6

答案 1 :(得分:0)

如果您要查找的格式只是A的非零元素列表,请在写入之前将其删除:

Ano0 = A(A ~= 0);
dlmwrite('file.csv',Ano0 ,',');

对于行之间的换行符,您可以循环遍历A

maskNo0 = A~=0;
for k = 1:size(A,1)
    dlmwrite('file.csv',A(k,maskNo0),'-append');
end

答案 2 :(得分:0)

试试这个:

str = mat2str(A);                 %// this gives [1 2 0 0 0;7 8 9 1 2;4 5 6 0 0]
str([1 end]) = [];                %// remove brackets
str = regexprep(str,' 0','');     %// remove zeros with their spaces
str = regexprep(str,';','\\n ');  %// change semicolons to line-feeds
fid = fopen('filename.csv','w');  %// open file for writing
fwrite(fid,str);                  %// write contents to file
fclose(fid);                      %// close file