Matlab數據導出

MATLAB中的數據導出(或輸出)可以理解為寫入檔。 MATLAB允許在其他應用程式中使用讀取ASCII檔的數據。 為此,MATLAB提供了幾個數據導出選項。

可以創建以下類型的檔:

  • 來自數組的矩形,有分隔符號的ASCII數據檔。
  • 日記(或日誌)檔的按鍵和結果文本輸出。
  • 使用fprintf等低級函數的專用ASCII檔。

MEX檔訪問寫入特定文本檔格式的C/C++或Fortran例程。

除此之外,還可以將數據導出到電子錶格(Excel)。

將數字數組導出為有分隔符號的ASCII數據檔有兩種方法 -

  • 使用save函數並指定-ascii限定符
  • 使用dlmwrite函數

使用save函數的語法是:

save my_data.out num_array -ascii

其中,my_data.out是創建的分隔ASCII數據檔,num_array是一個數字數組,-ascii是說明符。

使用dlmwrite函數的語法是:

dlmwrite('my_data.out', num_array, 'dlm_char')

其中,my_data.out是分隔的ASCII數據檔,num_array是數組,dlm_char是分隔符號。

示例

以下示例演示了這個概念。創建腳本檔並鍵入以下代碼 -

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

執行上面示例代碼,得到以下結果 -

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函數不能使用單元格數組作為輸入。要從單元格數組的內容創建一個分隔的ASCII檔,可以 -

  • 使用cell2mat函數將單元陣列轉換為矩陣
  • 或使用低級檔I/O函數導出單元格數組。

如果使用save函數將字元數組寫入ASCII檔,則會將ASCII等效字元寫入該檔。

例如,把一個單詞hello寫到一個檔 -

h = 'hello';
save textdata.out h -ascii
type textdata.out

MATLAB執行上述語句並顯示以下結果。這是8位ASCII格式的字串“hello”的字元。

1.0400000e+02   1.0100000e+02   1.0800000e+02   1.0800000e+02   1.1100000e+02

寫到日記檔

日記檔是MATLAB會話的活動日志。diary函數在磁片檔中創建會話的精確副本,不包括圖形。

打開diary函數,鍵入 -

diary

或者,可以給出日誌檔的名稱,比如 -

diary diary.log

關閉日記函數 -



可以在文本編輯器中打開日記檔。

將數據導出到具有低級I/O的文本數據檔

到目前為止,我們已經導出數組。 但是,您可能需要創建其他文本檔,包括數字和字元數據的組合,非矩形輸出檔或具有非ASCII編碼方案的檔。為了實現這些目的,MATLAB提供了低級別的fprintf函數。

在低級I/O檔活動中,在導出之前,需要使用fopen函數打開或創建一個檔,並獲取檔識別字。 默認情況下,fopen會打開一個只讀訪問的檔。所以應該指定寫入或附加的許可權,例如'w''a'

處理檔後,需要用fclose(fid)函數關閉它。

以下示例演示了這一概念 -

示例

創建腳本檔並在其中鍵入以下代碼 -

% 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

運行檔時,會顯示以下結果 -

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

上一篇: Matlab數據導入 下一篇: Matlab繪圖