Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-10, 20:48   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 如何在MATLAB中将字符串和矩阵写入.txt文件?

我需要将数据写入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'指定了'newline','pc'选项。需要\r以确保在记事本中打开输出文本文件时,矩阵的第一行显示在新行上。



更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 21:15


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.