2010-04-11 145 views
1

我在MATLAB中使用了以下功能以写入和读出4098浮点数:阅读浮点数字和字符串

写作:

fid = fopen(completepath, 'w'); 

fprintf(fid, '%1.30f\r\n', y) 

阅读:

data = textread(completepath, '%f', 4098); 

其中y包含4098个数字。我现在想在这些数据的末尾写入和读取3个字符串。我如何读取两种不同的数据类型?请帮帮我。提前致谢。

回答

2

这里是什么,我认为你想要做一个例子,使用TEXTSCAN读取文件,而不是TEXTREAD(将在MATLAB的未来版本中删除):

%# Writing to the file: 

fid = fopen(completepath,'w'); %# Open the file 
fprintf(fid,'%1.30f\r\n',y); %# Write the data 
fprintf(fid,'Hello\r\n');  %# Write string 1 
fprintf(fid,'there\r\n');  %# Write string 2 
fprintf(fid,'world!\r\n');  %# Write string 3 
fclose(fid);     %# Close the file 

%# Reading from the file: 

fid = fopen(completepath,'r');  %# Open the file 
data = textscan(fid,'%f',4098);  %# Read the data 
stringData = textscan(fid,'%s',3); %# Read the strings 
fclose(fid);      %# Close the file 
1

好了,你可以在任何时候写出来的字符串时,你可以利用下面的写入文件:

fprintf(fid, '%s', mystring); 

当然,你可能想要的东西更像是你给的形式:

fprintf(fid,'%s\r\n', mystring); 

而且你可以用字符串像这样混合的浮点:

fprintf(fid, '%1.30f %s\r\n', y, mystring); 

如果您正在处理混合数据类型,如果格式不是非常规的,你可能想使用fscanf而不是textread。例如,

data = fscanf(fid, '%s', 1); 

从文件读取一个字符串。

查看fscanf的帮助文件以获取有关如何使用它的更多信息。这些函数几乎是ANSI C函数(我的意思是fprintf和fscanf),所以你可以很容易地在网上找到关于它们的更多信息。