matlab以字符串读取文件探索

test.txt 文件的内容如下: (总共是4行)

title: test
11 22
line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2 line 2
line 3


fid = fopen('test.txt','r');
%注意每读取一行,指针指向下一行
line1=fgets(fid);%fgets 从文件中读取行,保留换行符 (换行符和回车符)
line2=fscanf(fid, '%d %d\n', 2);
line3=fgetl(fid);%fgetl 从文件中读取行,不带文件换行符
line4=fgetl(fid);
fclose(fid);


其中fscanf使用方法如下:

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

size是一个[m n]的向量,m为行,n为列(注意,这里读取的顺序是按列优先排列的)。如果size只有一个数,那代表行

format具体见http://www.mathworks.com/help/matlab/ref/fscanf.html#inputarg_formatSpec

常用有%d 整型,%f 浮点型, %s 字符型

%*d 表示省略整型数据,%*s表示不输出字符型数据






你可能感兴趣的:(Matlab)