如何在MATLAB中将字符串和矩阵写入.txt文件?

9

我需要在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解决方案。

4个回答

24

我认为解决你的问题只需要在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行终止符由回车和换行符组成,这也是在指定'newline','pc'选项时DLMWRITE所使用的。需要\r以确保矩阵的第一行出现在Notepad中打开输出文本文件时的新行上。


谢谢gnovice!你又帮了我一次! - Maddy
我有一个相关的问题: 这段代码在我的系统上可以正常运行。但是当我远程桌面连接到服务器并将其Matlab路径设置为我的本地matlab目录时,同样的代码无法设置文件。整个项目可以正确运行,但文件处理失败了。有什么建议吗?谢谢。 - Maddy
pathstr = 'C:/Documents and Settings/xxx/My Documents/MATLAB/Factor Production/Results/xxx' ; 当我在本地执行时,这个路径可以正常工作。但是,当我使用服务器并运行相同的文件组(通过设置路径)时,它会失败。我收到错误消息“没有这样的文件或目录”。该消息来自代码行:[fid,message] = fopen(fName,'w'); - Maddy
谢谢。我刚刚将结果输出到另一台服务器上。这很好地实现了目的!感谢你的帮助。 - Maddy

5

您不需要调用空矩阵。请尝试使用以下代码:

str = 'This is the matrix: ' ;
mat1 = [23 46 ; 56 67] ;
fName = 'output.txt';
fid = fopen('output.txt','w');
if fid>=0
    fprintf(fid, '%s\n', str)
    fclose(fid)
end
dlmwrite(fName, mat1, '-append', 'newline', 'pc', 'delimiter','\t');

2

你有两个dlmwrite()调用,第一个调用是在一个空矩阵上进行的,而第二个调用缺少'delimiter'选项。如果你在第二个调用中添加它会发生什么?


1

我遇到了类似的情况,需要在csv文件中添加一个标题。你可以使用dlmwrite命令并设置-delimiter参数为''来添加单行,具体如下所示:

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
header1 = 'A, B'
dlmwrite(fName, str, 'delimiter', '')
dlmwrite(fName, header1, '-append', 'delimiter', '')
dlmwrite(fName, mat1, '-append','delimiter', ',')

这会产生以下结果:
This is the matrix: 
A, B
23,46
56,67

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接