Getting Started with Matlab (file reading and writing)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.