MATLAB 讀取和寫入文字檔案

2021-09-06 20:27:41 字數 1316 閱讀 9436

一、讀取文字檔案

思路:1、用fopen來開啟乙個檔案控制代碼

2、用fgetl來獲得檔案中的一行,如果檔案已經結束,fgetl會返回-1

3、用fclose來關閉檔案控制代碼

比如,tim_grid_data.txt的內容如下:

0.1 0.1 151.031 -12.3144 -29.0245 3.11285 0.1 0.2 120.232 -2.53284 -8.40095 3.3348 0.1 0.3 136.481 -0.33173 -22.4462 3.598 0.1 0.4 184.16 -18.2706 -54.0658 2.51696 0.1 0.5 140.445 -6.99704 -21.2255 2.4202 0.1 0.6 127.981 0.319132 -29.8315 3.11317 0.1 0.7 106.174 -0.398859 -39.5156 3.97438 0.1 0.8 105.867 -20.1589 -13.4927 11.6488 0.1 0.9 117.294 -11.8907 -25.5828 4.97191 0.1 1 79.457 -1.42722 -140.482 0.726493 0.1 1.1 94.2203 -2.31433 -11.9207 4.71119

那麼可以用下面的**來讀取該文字檔案:

fid=fopen('tim_grid_data.txt','r'); best_data=; while 1     tline=fgetl(fid);     if ~ischar(tline),break;end     tline=str2num(tline);     best_data=[best_data;tline];

endfclose(fid);

這樣文字檔案中的內容就讀入到了best_data中了。

二、寫入文字檔案

思路:1、用fopen開啟乙個檔案控制代碼,但要用「w+」或「r+」等修飾符,具體參看help fopen

2、用fprintf寫入資料

3、用fclose來關閉檔案控制代碼

比如下面的程式:

fid=fopen('data.txt','a+'); fprintf(fid,'hello,tim\r\n'); fprintf(fid,''); a=rand(1,10); fprintf(fid,'%g\r\n',a); fclose(fid);

開啟data.txt檔案,可以看到:

hello,tim 0.655741

0.0357117 0.849129 0.933993 0.678735 0.75774 0.743132 0.392227 0.655478 0.171187

所以,用matlab來進行操作文字檔案是不是很簡單啊。

讀取和寫入文字檔案

read a text file 的這篇文章部分描述如何使用streamreader類來讀取文字的檔案。write a text file example 1 和 write a text file example 2 在各節說明了如何使用streamwriter類來向檔案寫入文字。讀取文字檔案 若...

vb讀取和寫入文字檔案

dim flname as string dim ofilenum as long dim sline as string dim ifilenum as long flname c dxfelement.dat if dir flname then kill flname end if ofile...

c 讀取 寫入 文字檔案

include include 讀寫檔案的標頭檔案 include using namespace std 1 文字檔案 寫檔案 1 包含標頭檔案 include 2 建立流物件 ofstream ofs 3 指定路徑和開啟方式 ofs.open 路徑,開啟方式 開啟方式 ios in 讀檔案開啟 ...