我需要将数据写入 MATLAB 中的 .txt 文件。我知道如何编写字符串 (fprintf
) 或 矩阵 (dlmwrite
),但我需要可以同时执行这两种操作的东西。下面我举个例子:
str = 'This is the matrix: ' ;
mat1 = [23 46 ; 56 67] ;
%fName
if *fid is valid*
fprintf(fid, '%s\n', str)
fclose(fid)
end
dlmwrite(fName, *emptymatrix*, '-append', 'delimiter', '\t', 'newline','pc')
dlmwrite(fName, mat1, '-append', 'newline', 'pc')
这工作正常,但有问题。文件的第一行是:
This is the matrix: 23,46
这不是我想要的。我想看看:
This is the matrix:
23 46
56 67
我该如何解决这个问题?我不能使用 for 循环和 printf
解决方案,因为数据量很大而且时间是个问题。
最佳答案
我认为要解决您的问题,您只需在 FPRINTF 中添加一个回车符 (\r
)语句并删除对 DLMWRITE 的第一次调用:
str = 'This is the matrix: '; %# A string
mat1 = [23 46; 56 67]; %# A 2-by-2 matrix
fName = 'str_and_mat.txt'; %# A file name
fid = fopen(fName,'w'); %# Open the file
if fid ~= -1
fprintf(fid,'%s\r\n',str); %# Print the string
fclose(fid); %# Close the file
end
dlmwrite(fName,mat1,'-append',... %# Print the matrix
'delimiter','\t',...
'newline','pc');
文件中的输出如下所示(数字之间有制表符):
This is the matrix:
23 46
56 67
注意: 一个简短的解释......在 FPRINTF 中需要 \r
的原因语句是因为 PC 行终止符由回车符和换行符组成,这是 DLMWRITE 使用的内容当指定了 'newline','pc'
选项时。需要 \r
以确保在记事本中打开输出文本文件时矩阵的第一行出现在新行上。
关于string - 如何在 MATLAB 中将字符串和矩阵写入 .txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4556971/