matlab fscanf用法

matlab fscanf用法

matlab中的fscanf的用法如下:

A=fscanf(fid,format)

[A, count]=fscanf(fid,format,size)

[A, count]=fscanf(fid,format,size)

个人感觉用的最多的是 这样的形式:

data = fscanf(fid,format,size);

期中data为读取内容的数组,他的大小由size决定,即如果size为2行3列,data即为【2,3】,如果size为[4 inf],则data为4行n列,而且data数据先按列填满4个,之后再换一列。size是一个[m n]的向量,

m为行,n为列(注意,这里读取的顺序是按列优先排列的,不明白的话可以看

下面的例子),若n取inf表示读到文件末尾。fid为fopen打开文件的返回值,

format是格式化参数(像printf、scanf)。

format包含txt内所有类型,%*d表示省略整型数据,例如

0.00 good 2

0.10 bot 3

1.02 yes 4

1.00 yes 5

1.00 yes 6

1.00 yes 3

1.00 yes 5

1.00 yes 6

1.00 yes 1

1.00 yes 3

1.00 yes 7

1.00 yes 3

1.00 yes 2

fid = fopen('E:\temp\test.txt', 'r');

a = fscanf(fid, '%f %*s %d ', [2 inf]) % It has two rows now.

fclose(fid)

解释下:第一列和第二列之间有四个空格,format也要四空格哦!有三列即三种类型,要有三种format,%*s即为不输出字符串型。结果为:

a =

Columns 1 through 11

0 0.1000 1.0200 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000

2.0000 3.0000 4.0000 5.0000 6.0000 3.0000 5.0000 6.0000 1.0000 3.0000 7.0000

Columns 12 through 13

1.0000 1.0000

3.0000 2.0000

fid = fopen('E:\temp\test.txt', 'r');

a = fscanf(fid, '%f %*s %*f ', 5) % It has two rows now.

fclose(fid)

a =

5.0000

0.1000

1.0200

1.0000

1.0000

举个小例子2:

路径+文件名:d:\moon.txt

内容:13,1,3.4

   3,2.1,23

1,12,2

   4,5.4,6

现在为了读取moon中的数据存在一个数组里,可以用如下方法

fd:\moon.txt');

data=fscanf(fid,'%f,%f,%f',[3,inf]) ;%这里得用单引号

fclose(fid);

这时data中的数据如下:

13 3 1 4

1 2.1 12 5.4

4 23 2 6

通常我们可能需要用引用数组中的某行或某列来画图,方法是data(m,:) 或者 data(:,n),即取得data数组的第m行或第n列。