Matlab入门学习(文件读写)

一、save,load

>> a=[1 2 3 4];
>> b=[4 5 6 7]

b =

     4     5     6     7

>> save('b.mat','a','b');%a file named b.mat will exit
>> clear
>> load b.mat
>> %load the data a and b

二、txt文件

假设在当前目录下有个txt文件data.txt,内容如下:

1 2 3
4 5 6
7 8 9

使用语句: load data.txt,当前就会多出一个变量,名字是data,内容就是上述文本中的内容,是一个矩阵

三、格式化读写

涉及到的函数:fopen,fscanf,fprintf,fclose;

fid=fopen('data.txt','r');
a=fscanf(fid,'%d%d%d',3);%read from fid,the number of elements is 3
b=fscanf(fid,'%d%d%d',3);%the rule of the middle params is the same as c language
c=fscanf(fid,'%d%d%d',3);
fclose(fid);
a
b
c
display('after write');
fid=fopen('data','w');
fprintf(fid,'%d %d %d
',c);
fprintf(fid,'%d %d %d
',b);
fprintf(fid,'%d %d %d
',a);
fclose(fid);

程序运行的结果:

a =

1
2
3


b =

4
5
6


c =

7
8
9

after write

在当前目录下会生成一个文件名字是data,双击之后可以看到里面的内容:

7 8 9
4 5 6
1 2 3

四、字符串读写

涉及到的函数sscanf,sprintf。

scanf从字符串中读数据:

>> a='1 2 3 4 5 6';

>> b=sscanf(a,'%d',3);

>> b

b =

1
2
3

sprintf向字符串中写入内容:

>> a=[1 2 3 4];

>> str=sprintf('this is a string contain : %d%d%d%d',a)

str =

this is a string contain : 1234

字符串拼接:strcat:

>> a='1 2 3'

a =

1 2 3

>> b='4 5 6'

b =

4 5 6

>> strcat(a,b)

ans =

1 2 34 5 6

数字转化为字符串:num2str(同理,字符串转化为数字使用函数(str2num函数)):

>> a=10

a =

10

>> b='num is ';
>> strcat(b,num2str(a))

ans =

num is10

原文地址:https://www.cnblogs.com/guanking19/p/5161884.html