6.1.3 fscanf函数读出数据
调用方式
A = fscanf(fid, format)
[A,count] = fscanf(fid, format, size)
输入参数
fid 同上
format 同上
size 决定读取多少数据其内容如下。
n表示将n个元素读入一个向量
inf读取到文件结尾,结果是一个向量
[m,n]读取的元素填满m行n列矩阵
输出参数
A 数据变量
count 读取值的个数
下面读出exp.txt文件。
>> fid = fopen('exp.txt',
'r'); % 'r'表示读取文件操作
>> a = fscanf(fid, '%g %g', [2
inf]);
>>fclose(fid)
>> a = a'
>> a
a =
0 1.0000
0.1000 1.1052
0.2000 1.2214
0.3000 1.3499
0.4000 1.4918
0.5000 1.6487
0.6000 1.8221
0.7000 2.0138
0.8000 2.2255
0.9000 2.4596
1.0000 2.7183
6.1.4 从文本文件中读入格式化数据
1.textread函数读取文本文件
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:\test3.txt
Q1 1 2