Mad*_*ddy 9 string file-io matlab matrix 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')
Run Code Online (Sandbox Code Playgroud)
这没关系,但有问题.该文件的第一行是:
This is the matrix: 23,46
Run Code Online (Sandbox Code Playgroud)
这不是我想要的.我想看看:
This is the matrix:
23 46
56 67
Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?我不能使用for循环和printf解决方案,因为数据很大,时间也是个问题.
gno*_*ice 24
我认为你要解决的问题是\r在你的FPRINTF语句中添加一个回车符()并删除对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');
Run Code Online (Sandbox Code Playgroud)
并且文件中的输出看起来像这样(在数字之间有选项卡):
This is the matrix:
23 46
56 67
Run Code Online (Sandbox Code Playgroud)
注意:一个简短的解释...... \r在FPRINTF语句中需要的原因是因为PC行终止符由回车符后跟换行符组成,这是DLMWRITE在'newline','pc'指定选项时使用的.的\r需要,以确保在记事本中打开该输出文本文件时在新的一行显示的矩阵的第一行.
您不需要空矩阵调用.试试这段代码:
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');
Run Code Online (Sandbox Code Playgroud)