我试图将矩阵写入txt文件。我设法做到了,但我不想在我的txt文件中包含任何0
。
我的矩阵看起来像这样:
5 0 0; 1 2 28; 1 3 60; 1 4 100; 1 5 108; 2 3 48; 2 4 83; 2 5 90; 3 4 41; 3 5 46; 4 5 12
我希望我的txt文件中的输出看起来像这样:
5; 1 2 28; 1 3 60; 1 4 100; 1 5 108; 2 3 48; 2 4 83; 2 5 90; 3 4 41; 3 5 46; 4 5 12
我怎么能这样做?
答案 0 :(得分:2)
代码:
%Given matrix is:
matrix= [5 0 0; 1 2 28; 1 3 60; 1 4 100; 1 5 108; 2 3 48; 2 4 83; 2 5 90; ...
3 4 41; 3 5 46; 4 5 12];
%Converting the matrix into a string and doing some adjustements
out=regexprep(mat2str(matrix),';','; ');
out=regexprep([' ',out(2:end-1)],' 0',''); % Now Removing zeros
fid=fopen('MyFile.txt','w+'); %Creating a file
%If your path is not set, either set it or give the full path in the above line
% like this, for example: 'D:\Assignment\MyFile.txt'
fprintf(fid, out(2:end)); %Writing data to the text file (excluding the added space)
fclose(fid); %Closing the text file
阅读mat2str
,regexprep
,fopen
,{{3}的文档}和fprintf
了解这些功能的详细信息。
输出: