1. 程式人生 > >MATLAB讀取和寫入文字檔案、excel檔案

MATLAB讀取和寫入文字檔案、excel檔案

在MATLAB中,來讀取和寫入文字檔案是很簡單的事。下面,就來簡單介紹下。

一、讀取文字檔案

思路:
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];
end
fclose(fid);

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

二、寫入文字檔案

思路:
1、用fopen開啟一個檔案控制代碼,但要用“w+”或“r+”等修飾符,具體參看help fopen
2、用fprintf寫入資料
3、用fclose來關閉檔案控制代碼

比如下面的程式:

fid=fopen('Data.txt','a+');
%'a+' :Open or create new file for reading and writing. Append data to the end of the file.
fprintf(fid,'Hello,Tim\r\n');
fprintf(fid,'http://blog.sina.com.cn/pengtim');
a=rand(1,10);
fprintf(fid,'%g\r\n',a); 
fclose(fid);

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

Hello,Tim
http://blog.sina
.com.cn/pengtim0.655741 0.0357117 0.849129 0.933993 0.678735 0.75774 0.743132 0.392227 0.655478 0.171187

三、Excel檔案寫入

%建立一個myExample.xlsx檔案,並寫入資料
values = {1, 2, 3 ; 4, 5, 'x' ; 7, 8, 9};
headers = {'First','Second','Third'};
xlswrite('myExample.xlsx',[headers; values]);

開啟myExample.xlsx,結果如下

這裡寫圖片描述

四、Excel檔案讀取

%.讀取xlsx檔案
filename = 'myExample.xlsx';
A = xlsread(filename)

得到結果如下

A =

     1     2     3
     4     5   NaN
     7     8     9