在MATLAB中,来读取和写入文本文件是很简单的事。下面,就来简单介绍下。如果有其他问题,请留言。

一、读取文本文件

思路:

1、用fopen来打开一个文件句柄

2、用fgetl来获得文件中的一行,如果文件已经结束,fgetl会返回-1

3、用fclose来关闭文件句柄

比如,TIM_Grid_Data.txt的内容如下:

0.1 0.1 151.031 -12.3144 -29.0245 3.11285 0.1 0.2 120.232 -2.53284 -8.40095 3.3348 0.1 0.3 136.481 -0.33173 -22.4462 3.598 0.1 0.4 184.16 -18.2706 -54.0658 2.51696 0.1 0.5 140.445 -6.99704 -21.2255 2.4202 0.1 0.6 127.981 0.319132 -29.8315 3.11317 0.1 0.7 106.174 -0.398859 -39.5156 3.97438 0.1 0.8 105.867 -20.1589 -13.4927 11.6488 0.1 0.9 117.294 -11.8907 -25.5828 4.97191 0.1 1 79.457 -1.42722 -140.482 0.726493 0.1 1.1 94.2203 -2.31433 -11.9207 4.71119

那么可以用下面的代码来读取该文本文件:

fid=fopen('TIM_Grid_Data.txt','r'); best_data=[]; while 1     tline=fgetl(fid);     if ~ischar(tline),break;end     tline=str2num(tline);     best_data=[best_data;tline];

end

fclose(fid);

这样文本文件中的内容就读入到了best_data中了。

二、写入文本文件

思路:

1、用fopen打开一个文件句柄,但要用“w+”或“r+”等修饰符,具体参看help fopen

2、用fprintf写入数据

3、用fclose来关闭文件句柄

比如下面的程序:

fid=fopen('Data.txt','a+'); fprintf(fid,'Hello,Tim\r\n'); fprintf(fid,'http://blog.sina.com.cn/pengtim'); a=rand(1,10); fprintf(fid,'%g\r\n',a); fclose(fid);

打开Data.txt文件,可以看到:

Hello,Tim http://blog.sina.com.cn/pengtim0.655741 0.0357117 0.849129 0.933993 0.678735 0.75774 0.743132 0.392227 0.655478 0.171187

所以,用MATLAB来进行操作文本文件是不是很简单啊。

posted on 2014-12-26 13:24  qqhfeng16  阅读(1537)  评论(0编辑  收藏  举报