First, 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 would exit>>Clear>>Load B.mat>>%load The data A and B
Second, TXT file
Suppose there is a TXT file data.txt in the current directory, the following:
1 2 3
4 5 6
7 8 9
Using the statement: Load Data.txt, the current will be more than a variable, the name is data, the content is the above text content, is a matrix
Third, the format of reading and writing
The functions involved: fopen,fscanf,fprintf,fclose;
Fid=fopen ('Data.txt','R'); a=FSCANF (FID,'%d%d%d',3);%read fromFid,the Number of elements is 3b=FSCANF (FID,'%d%d%d',3);%the rule of the middleparams isThe same asC Languagec=FSCANF (FID,'%d%d%d',3); fclose (FID); Abcdisplay ('After write'); FID=fopen ('Data','W'); fprintf (FID,'%d%d%d\n', c); fprintf (FID,'%d%d%d\n', b); fprintf (FID,'%d%d%d\n', a); fclose (FID);
The results of the program run:
A =
1
2
3
b =
4
5
6
c =
7
8
9
After write
In the current directory will generate a file name is data, double-click to see what is inside:
7 8 9
4 5 6
1 2 3
Iv. string reading and writing
The function sscanf,sprintf is involved.
scanf reading data from a string:
>> a= ' 1 2 3 4 5 6 ';
>> b=sscanf (A, '%d ', 3);
>> b
b =
1
2
3
sprintf writes the contents to the string:
>> a=[1 2 3 4];
>> str=sprintf (' This is a string contain:%d%d%d%d ', a)
str =
This is a string contain:1234
string concatenation: 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
The number is converted to a string: Num2str (in the same vein, string conversions are used for numeric functions (Str2Num functions)):
>> a=10
A =
10
>> b= ' num is ';
>> strcat (B,num2str (a))
Ans =
Num IS10
Getting Started with Matlab (file reading and writing)