登录论坛

查看完整版本 : [MATLAB基础] txt文档数据的格式化读取


yhcode
2010-07-04, 20:22
以前经常看到类似的问题,如怎么将txt文件中的数据导入(读入)matlab等,常用方法有load, 菜单操作(File->Import data),这两种方法对txt数据的格式要求比较严格,对于那些有一定说明的txt数据,往往得不到好的效果,这种情况下建议使用textscan函数,matlab help中的说明:
textscan
功能:Read formatted data from text file or string
调用形式:
C = textscan(fid, 'format')
C = textscan(fid, 'format', N)
C = textscan(fid, 'format', param, value,...)
C = textscan(fid, 'format', N, param, value,...)
C = textscan(str, ...)[C, position] = textscan(...)
例如,读取一个txt文件,格式如下:
LINE_OFF: +000837.00 pixels
SAMP_OFF: +002522.00 pixels
LAT_OFF: +32.72160000 degrees
LONG_OFF: -117.13360000 degrees
HEIGHT_OFF: +0036.000 meters
LINE_SCALE: +001685.00 pixels
SAMP_SCALE: +006977.00 pixels
LAT_SCALE: +00.01580000 degrees
LONG_SCALE: +000.07560000 degrees
HEIGHT_SCALE: +0223.000 meters
。。。。
用textscan读取的方法如下:
C = textscan(fp,'%s %f %s');
line_off = C{1,2}(1);
samp_off = C{1,2}(2);
lat_off = C{1,2}(3);
long_off = C{1,2}(4);
height_off = C{1,2}(5);
line_scale = C{1,2}(6);
samp_scale = C{1,2}(7);
lat_scale = C{1,2}(8);
long_scale = C{1,2}(9);
height_scale = C{1,2}(10);