如何用MATLAB读取大文本文件

MATLAB如何读取大文本文件分析

这里写图片描述

–读大文本关键函数–:textread, textscan

1 textread函数
语法:

[A, B, C, …] = textread(filename, format)
[A, B, C, …] = textread(filename, format, N)
[…] = textread(…, param, value, …)

说明(新版本已经提示弃用)见后续代码, 或者在命令行窗口使用 doc textread 打开查看

示例1
% img.txt 16进制的图像数据,大小30M ~ 200M
file = '../img.txt';
% 以字符串读出数据
data = textread( file, '%s' )';
% 计算字符个数
len = numel(dataIn);
k = 1;
% 使用hex2dec将16进制转换成10进制
data = hex2dec( data );

% 还原16进制数(数据为高低位8位需要变成16位原始数据)
for i = 1 : 2 : len - 1
    data(k) = dataIn( i ) + dataIn(i + 1) * 2^8;
    k = k + 1;
end

封装成函数

function data = readData( fileName )
% FILE size is less than 200M
    filename = fopen( fileName )
    dataIn = textread( filename, '%s' )';
    len = numel(dataIn);

    k = 1;
    dataIn = hex2dec( dataIn );
    for i = 1 : 2 : len - 1
        data(k) = dataIn( i ) + dataIn(i + 1) * 2^8;
        k = k + 1;
    end
    fclose(filename);
end

小结:实际测试中最大读取过300M的文本文件,

2 textscan函数
语法:

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) 将已打开的文本文件中的数据读取到元胞数组 C。该文本文件由文件标识符 fileID 指示。使用 fopen 可打开文件并获取 fileID 值。完成文件读取后,请调用 fclose( fileID ) 来关闭文件。

textscan 尝试将文件中的数据与 formatSpec 中的转换设定符匹配。textscan 函数在整个文件中按 formatSpec 重复扫描数据,直至 formatSpec 找不到匹配的数据时才停止。

示例
C = textscan(fileID, formatSpec, N) 按 formatSpec 读取文件数据 N 次,其中 N 是一个正整数。要在 N 个周期后从文件读取其他数据,请使用原 fileID 再次调用 textscan 进行扫描。如果通过调用具有相同文件标识符 ( fileID ) 的 textscan 恢复文件的文本扫描,则 textscan 将在上次终止读取的点处自动恢复读取。

示例
C = textscan(chr, formatSpec) 将字符向量 chr 中的文本读取到元胞数组 C 中。从字符向量读取文本时,对 textscan 的每一次重复调用都会从开头位置重新开始扫描。要从上次位置重新开始扫描,需要指定 position 输出参数。

textscan 尝试将字符向量 chr 中的数据与 formatSpec 中指定的格式匹配。

C = textscan(chr, formatSpec, N) 按 formatSpec N 次,其中 N 是一个正整数。

示例
C = textscan(…, Name, Value) 使用一个或多个 Name, Value 对组参数以及上述语法中的任何输入参数来指定选项。

示例
[ C, position ] = textscan( ) 在扫描结束时返回文件或字符向量中的位置作为第二个输出参数。对于文件,该值等同于调用 textscan 后再运行 ftell( fileID ) 所返回的值。对于字符向量,position 指示 textscan 读取了多少个字符。

示例2

% 依然考虑读取大量的16进制文本
% 这里只读取一帧的图片数据进来
% 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 : N1
    temp = cell2mat(file{i});
    temp = hex2dec(temp);
    img(:,i) = temp;
end

k = 1;
Img = zeros(1, M*N);
for i = 1 : M
    for j = 1 : 2: N1
        Img(k) = img(i, j) + img(i, j+1) * 2^8;
        k = k + 1;
    end
end

Img = reshape( Img, [N M] )';

figure, imshow(Img, [ ]);

这里写图片描述

  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值