2.8 儲(chǔ)存及讀取數(shù)據(jù)我們?cè)谑褂肕ATLAB過程中,免不了希望將運(yùn)算過程中的某些數(shù)據(jù)「儲(chǔ)存」起來,以便下次使用再「讀取」利 用?!竷?chǔ)存」和「讀取」的指令分別是save及load,而save的數(shù)據(jù)型態(tài)又分為:(1)雙位元格式 (binary format) 的 MAT-file,(2) ASCII 格式的 ASCII-file。MAT-file 是以雙位元字元儲(chǔ)存,可讓電腦在讀出/入(input/output) 速率加 快,其格式為test.mat(test為檔名),MATLAB將檔案的型態(tài)預(yù)設(shè)為MAT-file;而ASCII-file則是以可辨識(shí)的字元 儲(chǔ)存,但會(huì)降低電腦在讀出/入的速率,其格式為test.dat(test為檔名)。如果你的數(shù)據(jù)是只在MATLAB中產(chǎn)生 及被使用,那最好使用MAT-file。ASCII-file則必須用在當(dāng)數(shù)據(jù)檔要為其它不是MATLAB的應(yīng)用軟體讀取時(shí)。 另外要注意,當(dāng)save成MAT檔是儲(chǔ)存變數(shù)本身,而非直接儲(chǔ)存變數(shù)的數(shù)據(jù);而save成ASCII檔則是直接儲(chǔ)存變數(shù)的數(shù)值。 這二者儲(chǔ)存的差異,造成在讀取MAT檔和ASCII檔的數(shù)據(jù)有所不同,詳見以下的范例。 須注意的是在儲(chǔ)存及讀取數(shù)據(jù)時(shí),MAT-file或是ASCII-file的檔最好為矩陣型態(tài),否則可能在讀取時(shí)有困難。數(shù) 據(jù)儲(chǔ)存成矩陣的大小可以為m×n,其中m是列的數(shù)目,n則為行的數(shù)目。 以下就是幾個(gè)save, load的使用范例 >> x=1:5; y=11:15; % 先產(chǎn)生二個(gè)列陣列 (row array} x, y >> save data1 x y % 是將 x,y 二個(gè)變數(shù)的數(shù)值存入 data1 這個(gè)MAT-file, %即data1其實(shí)是data1.mat。data1.mat 的內(nèi)容為變數(shù)x, y,而非(1:5, 11:15) 的數(shù)據(jù) >> save data2.dat x y -ascii % 如果要將data1改以ASCII格式儲(chǔ)存,則須加上-ascii % 的選項(xiàng)。data2.dat 的內(nèi)容為(1:5, 11:15) 的數(shù)據(jù) >> type data2.dat % type 指令可以將 data2.dat 的內(nèi)容列出 >> load data1 % 讀取 data1.mat 檔 >> x, y % 叫出 data1.mat中的變數(shù)來讀取其內(nèi)容(1:5, 11:15) >> load data2.dat % 讀取 data2.dat 檔 >> x2=data2(1,:); y2=data2(2,:); % 將data2中的第一及第二列數(shù)據(jù)分別以x2及y2 %變數(shù)讀入,之后在運(yùn)算中即可使用這二列數(shù)據(jù) >> x=21:25; y=31:35; >> save data3.dat x y -ascii >> load data3.dat; >> x3=data3(1,:); y3=data3(2,:); % 將data3中的第一及第二列數(shù)據(jù)分別以x3及y3 變數(shù)讀入 %,之后在運(yùn)算中即可使用這二列數(shù)據(jù) >> A=[1 2 3; 4 5 6]; >> save data4.dat A -ascii %是將A陣列的數(shù)值存入data4這個(gè)ASCII-file >> load data4.dat >> x4=data4(:,1); % 令 x4 為 data4 的第一行數(shù)據(jù) >> y4=data4(:,2); % 令 y4 為 data4 的第二行數(shù)據(jù) >> z4=data4(:,3); % 令 z4 為 data4 的第三行數(shù)據(jù) |
|