Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我需要将数据写入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以确保在记事本中打开输出文本文件时,矩阵的第一行显示在新行上。 更多&回答... |
![]() |
![]() |