Matlab 中的 textread textscan 读取文本文件
1.MATLAB 从文本文件中读取格式化的数据函数是 textread。
调用方式
[A,B,C,...] = textread('filename','format')
[A,B,C,...] = textread('filename','format',N)
[...] = textread(...,'param','value',...)
输入参数
'filename' 需要读取的数据文件
'format' 每行各个数据格式
N 读取数据时使用 N 次。
当调用 textread 函数时会按照指定的格式从'filename'中读取数据,并将数据分别保存在变量
A,B,C 中,直到文件内容被读完为止。
下面是读取 c:\中的 test3.txt 文件操作。
>> !type c: est3.txt
Q1 1 2
Q2 3 4
>> [a1 a2 a3]=textread('c: est3.txt','%s %f %f')
a1 =
'Q1'
'Q2'
a2 =
1
3
a3 =
2
4
这样文件 test3.txt 中的每行分别读入变量 a1、a2、a3。
2.TextScan 函数读取文本数据
对于具有多行文字说明文本数据文件,最好的办法则是用 textscan,或者 fscanf 读取。
调用方式
C = textscan(fid, 'format')
C = textscan(fid, 'format', N)
C = textscan(fid, 'format', param, value, ...)
C= textscan(fid, 'format', N, param, value, ...)
输入参数
fid 为 fopen 命令返回的文件标识符
format 是一个字符串变量,表示读取数据及数据转换的规则。Format 中包含了多种方式,
其内容如表 6.5 所示。
format 内容
数 据 转 换
规则
说 明
%n 读取一个数字并转换为 double