如何用MATLAB读取大文本文件
–讀大文本關(guān)鍵函數(shù)–:textread, textscan
1 textread函數(shù)
語法:
[A, B, C, …] = textread(filename, format)
[A, B, C, …] = textread(filename, format, N)
[…] = textread(…, param, value, …)
說明(新版本已經(jīng)提示棄用)見后續(xù)代碼, 或者在命令行窗口使用 doc textread 打開查看
示例1
% img.txt 16進制的圖像數(shù)據(jù),大小30M ~ 200M file = '../img.txt'; % 以字符串讀出數(shù)據(jù) data = textread( file, '%s' )'; % 計算字符個數(shù) len = numel(dataIn); k = 1; % 使用hex2dec將16進制轉(zhuǎn)換成10進制 data = hex2dec( data );% 還原16進制數(shù)(數(shù)據(jù)為高低位8位需要變成16位原始數(shù)據(jù)) for i = 1 : 2 : len - 1data(k) = dataIn( i ) + dataIn(i + 1) * 2^8;k = k + 1; end封裝成函數(shù)
function data = readData( fileName ) % FILE size is less than 200Mfilename = fopen( fileName )dataIn = textread( filename, '%s' )';len = numel(dataIn);k = 1;dataIn = hex2dec( dataIn );for i = 1 : 2 : len - 1data(k) = dataIn( i ) + dataIn(i + 1) * 2^8;k = k + 1;endfclose(filename); end小結(jié):實際測試中最大讀取過300M的文本文件,
2 textscan函數(shù)
語法:
C = textscan(fileID, formatSpec)
C = textscan(fileID, formatSpec, N)
C = textscan(chr, formatSpec)
C = textscan(chr, formatSpec, N)
C = textscan(…, Name, Value)
[ C, position ] = textscan( … )
說明:
C = textscan(fileID, formatSpec) 將已打開的文本文件中的數(shù)據(jù)讀取到元胞數(shù)組 C。該文本文件由文件標識符 fileID 指示。使用 fopen 可打開文件并獲取 fileID 值。完成文件讀取后,請調(diào)用 fclose( fileID ) 來關(guān)閉文件。
textscan 嘗試將文件中的數(shù)據(jù)與 formatSpec 中的轉(zhuǎn)換設(shè)定符匹配。textscan 函數(shù)在整個文件中按 formatSpec 重復(fù)掃描數(shù)據(jù),直至 formatSpec 找不到匹配的數(shù)據(jù)時才停止。
示例
C = textscan(fileID, formatSpec, N) 按 formatSpec 讀取文件數(shù)據(jù) N 次,其中 N 是一個正整數(shù)。要在 N 個周期后從文件讀取其他數(shù)據(jù),請使用原 fileID 再次調(diào)用 textscan 進行掃描。如果通過調(diào)用具有相同文件標識符 ( fileID ) 的 textscan 恢復(fù)文件的文本掃描,則 textscan 將在上次終止讀取的點處自動恢復(fù)讀取。
示例
C = textscan(chr, formatSpec) 將字符向量 chr 中的文本讀取到元胞數(shù)組 C 中。從字符向量讀取文本時,對 textscan 的每一次重復(fù)調(diào)用都會從開頭位置重新開始掃描。要從上次位置重新開始掃描,需要指定 position 輸出參數(shù)。
textscan 嘗試將字符向量 chr 中的數(shù)據(jù)與 formatSpec 中指定的格式匹配。
C = textscan(chr, formatSpec, N) 按 formatSpec N 次,其中 N 是一個正整數(shù)。
示例
C = textscan(…, Name, Value) 使用一個或多個 Name, Value 對組參數(shù)以及上述語法中的任何輸入?yún)?shù)來指定選項。
示例
[ C, position ] = textscan( ) 在掃描結(jié)束時返回文件或字符向量中的位置作為第二個輸出參數(shù)。對于文件,該值等同于調(diào)用 textscan 后再運行 ftell( fileID ) 所返回的值。對于字符向量,position 指示 textscan 讀取了多少個字符。
示例2
% 依然考慮讀取大量的16進制文本 % 這里只讀取一幀的圖片數(shù)據(jù)進來 % C = textscan(fileID, formatSpec, N) filename = fopen( 'object.txt' ); format = '%s'; M = 512; N = 640; N1 = 1280; img = zeros(M, N1); % Test one frame % N1 為一行有N1列,M為一列有M行 file = textscan(filename, repmat(format, [1 N1]), M); for i = 1 : N1temp = cell2mat(file{i});temp = hex2dec(temp);img(:,i) = temp; endk = 1; Img = zeros(1, M*N); for i = 1 : Mfor j = 1 : 2: N1Img(k) = img(i, j) + img(i, j+1) * 2^8;k = k + 1;end endImg = reshape( Img, [N M] )';figure, imshow(Img, [ ]);
總結(jié)
以上是生活随笔為你收集整理的如何用MATLAB读取大文本文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: establish connection
- 下一篇: 怎么保存html,怎么保存整个网页,教你