我在MATLAB中使用了以下功能以寫入和讀出4098浮點數:閱讀浮點數字和字符串
寫作:
fid = fopen(completepath, 'w');
fprintf(fid, '%1.30f\r\n', y)
閱讀:
data = textread(completepath, '%f', 4098);
其中y包含4098個數字。我現在想在這些數據的末尾寫入和讀取3個字符串。我如何讀取兩種不同的數據類型?請幫幫我。提前致謝。
我在MATLAB中使用了以下功能以寫入和讀出4098浮點數:閱讀浮點數字和字符串
寫作:
fid = fopen(completepath, 'w');
fprintf(fid, '%1.30f\r\n', y)
閱讀:
data = textread(completepath, '%f', 4098);
其中y包含4098個數字。我現在想在這些數據的末尾寫入和讀取3個字符串。我如何讀取兩種不同的數據類型?請幫幫我。提前致謝。
這裏是什麼,我認爲你想要做一個例子,使用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
好了,你可以在任何時候寫出來的字符串時,你可以利用下面的寫入文件:
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),所以你可以很容易地在網上找到關於它們的更多信息。