我如何写字符串和矩阵到MATLAB中的.txt文件? [英] How can I write strings and matrices to a .txt file in MATLAB?
问题描述
fprintf
)或矩阵( dlmwrite
),但是我需要能够做到这一点的东西。我将在下面给出一个例子: str ='这是矩阵:';
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')
这个工作正常,但有问题。该文件的第一行是:
pre $ 这是矩阵:23,46
这不是我想要的。我想看看:
这是矩阵:
23 46
56 67
我该如何解决这个问题?我不能使用for循环和 printf
解决方案,因为数据是巨大的,时间是一个问题。
我认为你所要解决的问题是把一个回车( \r
)添加到你的 FPRINTF 语句并将第一个调用移除到 DLMWRITE :
str ='这是矩阵:'; %#A字符串
mat1 = [23 46; 56 67]; %#A 2 * 2矩阵
fName ='str_and_mat.txt'; %#文件名
fid = fopen(fName,'w'); %#打开文件
if fid〜= -1
fprintf(fid,'%s\r\\\
',str); %#打印字符串
fclose(fid); %#关闭文件
end
dlmwrite(fName,mat1,' - append',...%#打印矩阵
'delimiter','\t',...
'newline','pc');
文件中的输出如下所示(带有数字之间的选项卡):
这是矩阵:
23 46
56 67
I need to write data to a .txt file in MATLAB. I know how to write strings ( This works okay, but with a problem. The first line of the file is: Which is not what I want. I want to see: How can I solve this? I can't use a for loop and I think all you have to do to fix your problem is add a carriage return ( And the output in the file looks like this (with tabs between the numbers): 这篇关于我如何写字符串和矩阵到MATLAB中的.txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
注意:一个简短的解释...需要 \\ \\ r
在 FPRINTF 声明中是因为一个PC行终止符由一个回车符和一个换行符组成,这是由'newline','pc'选项时,需要 \ r
来确保在记事本中打开输出文本文件时,矩阵的第一行出现在新行上。fprintf
) or matrices (dlmwrite
), but I need something that can do both of them. I'll give an example below: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
printf
solution as the data is huge and time is an issue.\r
) to your FPRINTF statement and remove the first call to 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
NOTE: A short explanation... the reason for needing the \r
in the FPRINTF statement is because a PC line terminator is comprised of a carriage return followed by a line feed, which is what is used by DLMWRITE when the 'newline','pc'
option is specified. The \r
is needed to ensure the first line of the matrix appears on a new line when opening the output text file in Notepad.