"MATLAB" reads and writes to a text file

Source: Internet
Author: User

In MATLAB, it is easy to read and write text files. Here's a quick introduction. If you have any other questions, please leave a message.

One, read the text file

Ideas:

1. Open a file handle with fopen

2, use Fgetl to get a line in the file, if the file has ended, Fgetl will return 1

3, use Fclose to close the file handle

For example, the contents of Tim_grid_data.txt are as follows:

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

You can then use the following code to read the text file:

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);

The contents of this text file are enrolled in the Best_data.

Second, write to the text file

Ideas:

1, open a file handle with fopen, but to use "w+" or "r+" and other modifiers, specifically see Help fopen

2. Write Data with fprintf

3, use Fclose to close the file handle

For example, the following program:

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);

Opening a Data.txt file, you can see:

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

So, using MATLAB to manipulate the text file is not very simple AH.

"MATLAB" reads and writes to a text file

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.