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

标签 string matlab matrix file-io text-files

我需要将数据写入 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/

相关文章:

java - 检查数组中的特定元素是否包含某个字符串。然后删除该元素

java - 如何优化代码以始终使用对 String 的相同引用而不增加内存使用量?

python - 合并 2 个数组以获得 python 中的唯一值

r - 如何在R中重复减去数据矩阵的行

r - 如何将观察的存在或不存在转换为具有这种格式的二进制事件计数的矩阵?

c - 在c中将char指针写入控制台

matlab - 结构域是函数matlab

matlab - 获取矩阵中最大值的位置

matlab - 如何找到整个二值图像的质心?

python - 使用 numpy 将矩阵 int 值映射到 str 的有效方法