| MATLAB Function Reference | ![]() |
Graphical Interface
除了使用 textread 指令外,也可使用輸入精靈(Import Wizard)。欲執行輸入精靈(Import
Wizard),請選擇檔案(File)中的輸入資料(Import data)。
Syntax
[A,B,C,...] = textread('filename','format')
[A,B,C,...] = textread('filename','format',N)
[...] = textread(...,'param','value',...)
Description
[A,B,C,...] = textread('filename','format')
依照 format 格式讀取檔案資料 str 並存入 A, B, C 等變數,直到讀完整個檔案資料。textread 指令對於讀取已知格式的檔案是相當有用的。不管是 fixed 還是 free 的檔案格式都可以處理。
textread 指令對應、轉換輸入的字元組。每一筆輸入欄位即為沒有空白字元而延伸到下個空白字元或是定義符號的字串,或是最大欄位長度的字串。連續出現的定義符號是有特殊意義的,但是連續的空白字元則會被視為只有一個空白字元。
依字串 format 來決定回傳值的個數及資料型態。回傳值的個數和字串
format 中決定項目的個數是相同的。同時,字串 format 支援 C 語言中
fscanf 程序的協定。字串 format 的使用方法列在下表。若在字串
format 中有空白字元,則一律忽略。
[A,B,C,...] = textread('filename','format',N)
依 format 格式重覆 N 次讀取檔案,N 為一大於 0 整數,若 N 小於 0 ,則 textread 將讀完整個檔案才結束。
[...] = textread(...,'param','value',...)
依照 param/value 來決定 textread 的功用,param/value 的用法列在下面的表格中。
範例 1 - 使用 % 讀取檔案的欄位
Sally Type1 12.34 45 Yes
[names,types,x,y,answer] = textread('mydata.dat','%s %s %f ...
%d %s',1)
names =
'Sally'
types =
'Type1'
x =
12.34000000000000
y =
45
answer =
'Yes'
範例 2 - 讀取檔案內容,但不包括浮點數
Sally Type1 12.34 45 Yes
[names,types,y,answer] = textread('mydata.dat','%9c %5s %*f ...
%2d %3s',1)
names =
Sally
types =
'Type1'
y =
45
answer =
'Yes'
在這個範例中,format 字串 %*f 指令造成 textread 忽略了檔案中的浮點數 12.34。
範例 3 - 使用文字去省略讀取相配對應的字體
Sally Type1 12.34 45 Yes
[names,typenum,x,y,answer] = textread('mydata.dat','%s Type%d %f
%d %s',1)
names =
'Sally'
typenum =
1
x =
12.34000000000000
y =
45
answer =
'Yes'
在這個範例中, 指令造成了第二欄的字體 format 字串 Type%dType 被忽略,而第二欄剩下的值會以正整數的型態被讀取,也就是 1。
範例 4 - 將 M 檔案讀進存取字串的陣列中
file = textread('fft.m','%s','delimiter','\n','whitespace','');
See Also
| Text Properties | textwrap | ![]() |