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

How to create a CSV file by removing zeros from Matlab Array

我有一个 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 文件吗?

如果您要查找的格式只是 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

试试这个:

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

一种方法 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