MATLAB中的數(shù)據(jù)導(dǎo)出(或輸出)可以理解為寫入文件。 MATLAB允許在其他應(yīng)用程序中使用讀取ASCII文件的數(shù)據(jù)。 為此,MATLAB提供了幾個數(shù)據(jù)導(dǎo)出選項。
可以創(chuàng)建以下類型的文件:
fprintf等低級函數(shù)的專用ASCII文件。MEX文件訪問寫入特定文本文件格式的C/C++或Fortran例程。
除此之外,還可以將數(shù)據(jù)導(dǎo)出到電子表格(Excel)。
將數(shù)字?jǐn)?shù)組導(dǎo)出為有分隔符的ASCII數(shù)據(jù)文件有兩種方法 -
save函數(shù)并指定-ascii限定符dlmwrite函數(shù)使用save函數(shù)的語法是:
save my_data.out num_array -ascii
其中,my_data.out是創(chuàng)建的分隔ASCII數(shù)據(jù)文件,num_array是一個數(shù)字?jǐn)?shù)組,-ascii是說明符。
使用dlmwrite函數(shù)的語法是:
dlmwrite('my_data.out', num_array, 'dlm_char')
其中,my_data.out是分隔的ASCII數(shù)據(jù)文件,num_array是數(shù)組,dlm_char是分隔符。
以下示例演示了這個概念。創(chuàng)建腳本文件并鍵入以下代碼 -
num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];
save array_data1.out num_array -ascii;
type array_data1.out
dlmwrite('array_data2.out', num_array, ' ');
type array_data2.out
執(zhí)行上面示例代碼,得到以下結(jié)果 -
Trial>> num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];
save array_data1.out num_array -ascii;
type array_data1.out
dlmwrite('array_data2.out', num_array, ' ');
type array_data2.out
1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00
4.0000000e+00 5.0000000e+00 6.0000000e+00 7.0000000e+00
7.0000000e+00 8.0000000e+00 9.0000000e+00 0.0000000e+00
1 2 3 4
4 5 6 7
7 8 9 0
請注意,保存save -ascii命令和dlmwrite函數(shù)不能使用單元格數(shù)組作為輸入。要從單元格數(shù)組的內(nèi)容創(chuàng)建一個分隔的ASCII文件,可以 -
cell2mat函數(shù)將單元陣列轉(zhuǎn)換為矩陣如果使用save函數(shù)將字符數(shù)組寫入ASCII文件,則會將ASCII等效字符寫入該文件。
例如,把一個單詞hello寫到一個文件 -
h = 'hello';
save textdata.out h -ascii
type textdata.out
MATLAB執(zhí)行上述語句并顯示以下結(jié)果。這是8位ASCII格式的字符串“hello”的字符。
1.0400000e+02 1.0100000e+02 1.0800000e+02 1.0800000e+02 1.1100000e+02
日記文件是MATLAB會話的活動日志。diary函數(shù)在磁盤文件中創(chuàng)建會話的精確副本,不包括圖形。
打開diary函數(shù),鍵入 -
diary
或者,可以給出日志文件的名稱,比如 -
diary diary.log
關(guān)閉日記函數(shù) -
可以在文本編輯器中打開日記文件。
到目前為止,我們已經(jīng)導(dǎo)出數(shù)組。 但是,您可能需要創(chuàng)建其他文本文件,包括數(shù)字和字符數(shù)據(jù)的組合,非矩形輸出文件或具有非ASCII編碼方案的文件。為了實現(xiàn)這些目的,MATLAB提供了低級別的fprintf函數(shù)。
在低級I/O文件活動中,在導(dǎo)出之前,需要使用fopen函數(shù)打開或創(chuàng)建一個文件,并獲取文件標(biāo)識符。 默認(rèn)情況下,fopen會打開一個只讀訪問的文件。所以應(yīng)該指定寫入或附加的權(quán)限,例如'w'或'a'。
處理文件后,需要用fclose(fid)函數(shù)關(guān)閉它。
以下示例演示了這一概念 -
示例
創(chuàng)建腳本文件并在其中鍵入以下代碼 -
% create a matrix y, with two rows
x = 0:10:100;
y = [x; log(x)];
% open a file for writing
fid = fopen('logtable.txt', 'w');
% Table Header
fprintf(fid, 'Log Function\n\n');
% print values in column order
% two values appear on each row of the file
fprintf(fid, '%f %f\n', y);
fclose(fid);
% display the file created
type logtable.txt
運(yùn)行文件時,會顯示以下結(jié)果 -
Log Function
0.000000 -Inf
10.000000 2.302585
20.000000 2.995732
30.000000 3.401197
40.000000 3.688879
50.000000 3.912023
60.000000 4.094345
70.000000 4.248495
80.000000 4.382027
90.000000 4.499810
100.000000 4.605170