登录论坛

查看完整版本 : 如何在MATLAB中将字符串和矩阵写入.txt文件?


poster
2019-12-10, 20:48
我需要将数据写入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 (http://www.mathworks.com/help/techdoc/ref/fprintf.html)语句中添加一个回车符( \r )并删除对DLMWRITE (http://www.mathworks.com/help/techdoc/ref/dlmwrite.html)的第一个调用:

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 (http://www.mathworks.com/help/techdoc/ref/fprintf.html)语句中需要\r的原因是因为PC行终止符由回车符和换行符组成,这是DLMWRITE (http://www.mathworks.com/help/techdoc/ref/dlmwrite.html)在'newline','pc'指定了'newline','pc'选项。需要\r以确保在记事本中打开输出文本文件时,矩阵的第一行显示在新行上。



更多&回答... (https://stackoverflow.com/questions/4556971)