前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Matlab 读写文件

Matlab 读写文件

作者头像
week
发布2018-08-24 15:36:24
5360
发布2018-08-24 15:36:24
举报
文章被收录于专栏:用户画像

一、读取文本文件 思路: 1、用fopen来打开一个文件句柄 2、用fgetl来获得文件中的一行,如果文件已经结束,fgetl会返回-1 3、用fclose来关闭文件句柄

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
fid=fopen('read.txt','r');
data=[];
while 1
    tline=fgetl(fid);%读取一行
    if ~ischar(tline),break;
    end %if与end是一对标记
    tline=str2num(tline);%字符串转化为数字
    data=[data;tline];%将tline存取数组
end
data;%显示数据
fclose(fid);

这样文本文件中的内容就读入到了data中了。 二、写入文本文件 思路:

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

'r'

Open file for reading.

'w'

Open or create new file for writing. Discard existing contents, if any.

'a'

Open or create new file for writing. Append data to the end of the file.

'r+'

Open file for reading and writing.

'w+'

Open or create new file for reading and writing. Discard existing contents, if any.

'a+'

Open or create new file for reading and writing. Append data to the end of the file.

'A'

Open file for appending without automatic flushing of the current output buffer.

'W'

Open file for writing without automatic flushing of the current output buffer.

2、用fprintf写入数据 3、用fclose来关闭文件句柄

比如下面的程序:

代码语言:javascript
复制
fid=fopen('write.txt','a+');
fprintf(fid,'Hello,world\r\n');
a=rand(1,10);
fprintf(fid,'%g\r\n',a);
fclose(fid);

运行程序,就会生成write.txt

代码语言:javascript
复制
Hello,world
0.157613
0.970593
0.957167
0.485376
0.80028
0.141886
0.421761
0.915736
0.792207
0.959492

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年09月11日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档