• 沒有找到結果。

A ,..., A incolumnorder,andwritesthedatatoatextfile. fprintf ( fid , format , A ,..., A )appliesthe format toallelementsofarrays . Recallthat fprintf ( format , A ,..., A )formatsdataanddisplaystheresultsonthescreen fprintf

N/A
N/A
Protected

Academic year: 2022

Share "A ,..., A incolumnorder,andwritesthedatatoatextfile. fprintf ( fid , format , A ,..., A )appliesthe format toallelementsofarrays . Recallthat fprintf ( format , A ,..., A )formatsdataanddisplaystheresultsonthescreen fprintf"

Copied!
33
0
0

加載中.... (立即查看全文)

全文

(1)

fprintf

Recall that fprintf(format, A1, ..., An) formats data and displays the results on the screen1.

fprintf(fid , format, A1, . . . , An) applies the format to all elements of arrays A1, . . . , An in column order, and writes the data to a text file.

format: Format of the output fields, specified as a string.

A1, . . . , An: arrays.

1Recall disp.

(2)

Recall that MATLAB reserves fid s 1 and 2 for standard output on the screen, and standard error, respectively.

fprintf(1, ’This is standard output!\n’);

fprintf(2, ’This is standard error!\n’);

sprintf(formatSpec, A1, ..., An), similar to fprintf but returns the results as a string.

(3)

Example

fprintf can print multiplenumeric values andliteral text to the screen.

1 A=[9.9 8.8 7.7; 9900 8800 7700];

2 format='X is %4.2f meters or %8.3f mm\n';

3 fprintf(format,A) % print on the screen

1 >>

2

3 X is 9.90 meters or 9900.000 mm

4 X is 8.80 meters or 8800.000 mm

5 X is 7.70 meters or 7700.000 mm

%4.2f specifies that the first value in each line of output is a floating-point number with a field width of four digits, including two digits after the decimal point.

Can you explain %8.3f?

(4)

Escape Characters

%%: Percent character

\\: Backslash

\b: Backspace

\n: New line

\t: Horizontal tab

(5)

format

Integer, signed: %d or %i Integer, unsigned

%u: Base 10

%o: Base 8

%x: Base 16 Floating-point number2

%f: Fixed-point notation

%e: Exponential notation, such as 3.141593e+00 Characters

%c: Single character

%s: String

Note that the % can be followed by an optional field width to handle fixed width fields.

2SeeIEEE 754.

(6)

Example: grep in UNIX/Linux-like Systems

findstr(S 1, S 2) returns the starting indices of any occurrences of the shorter of the two strings in the longer.

1 function grep(filename, pattern)

2 fid=fopen(filename, 'r');

3 line number=1;

4 while feof(fid)==0

5 line=fgetl(fid);

6 matched=findstr(line, pattern);

7 if ~isempty (matched) % tell if matched is ...

empty array

8 fprintf('%d: %s \n', line number, line);

9 end

10 line number=line number + 1;

11 end

12 fclose(fid);

(7)

1 >> grep('grep.m','matched')

2

3 6: matched=findstr(line, pattern);

4 7: if ~isempty (matched) % tell if matched is ...

empty array

(8)

Exercise

Write a short table of the exponential function to a text file called “exp.txt”, which looks like:

1 x exp(x)

2 0.00 1.00000000

3 0.10 1.10517092

4 0.20 1.22140276

5 0.30 1.34985881

6 0.40 1.49182470

7 0.50 1.64872127

8 0.60 1.82211880

9 0.70 2.01375271

10 0.80 2.22554093

11 0.90 2.45960311

12 1.00 2.71828183

(9)

1 clear all;

2 clc;

3 % main

4 x=0:.1:1;

5 A=[x', (exp(x))']; % recall that ' is a ...

transposition operator.

6 fid=fopen('exp.txt', 'w');

7 fprintf(fid, '%6s %12s\n', 'x', 'exp(x)');

8 fprintf(fid, '%6.2f %12.8f\n', A);

9 fclose(fid);

10 dos('start exp.txt'); % Open exp.txt

dos(0command0), for Windows systems, calls upon the shell to execute the given command .

Try dos(’start www.facebook.com’).

(10)

fscanf

A=fscanf(fid , format, size) reads data from the file specified by file identifier fid , converts it according to the specified format string, and returns it in matrix A.

fscanf populates A in column order.

fscanf can be used to skip specific characters in a sample file, and return only numeric data.

(11)

Example

1 clear all;

2 clc

3 str={

4 ['78' char(176) 'C'];

5 ['72' char(176) 'C'];

6 ['64' char(176) 'C'];

7 ['66' char(176) 'C'];

8 ['49' char(176) 'C']};

9 % char(176) is the symbol of degree

10 fid=fopen('temperature.txt', 'w');

11 for i=1:length(str)

12 fprintf(fid, '%s\n', str{i});

13 end

14 fclose(fid);

15 % main

16 fid=fopen('temperature.txt', 'r');

17 [A, count]=fscanf(fid, ['%d' char(176) 'C'])

18 fclose(fid);

(12)

1 >>

2

3 A =

4

5 78

6 72

7 64

8 66

9 49

10 11

12 count =

13

14 5

(13)

Binary Files

fread(fid ,size,precision) interprets values in the file according to the form and size described by precision.

fwrite(fid , A, precision) translates the values of A according to the form and size described by precision.

(14)

Valid entries forsize are:

N: read N elements into a column vector.

inf : read to the end of the file.

[M, N]: read elements to fill an M-by-N matrix, in column order.

Valid entries forprecision are:

’uchar’: unsigned integer, 8 bits.

’int64’: integer, 64 bits.

’uint64’: unsigned integer, 64 bits.

’float64’: floating point, 64 bits.

Note that “64” can be replaced by 8, 16, and 32.

(15)

Example

Create a binary file containing a 3-by-3 magic square, whose element is stored as 4-byte integers.

1 clear all;

2 clc

3 % main

4 A=magic(3)

5 fid = fopen('magic3.txt', 'w');

6 fwrite(fid, A, 'int32');

7 fclose(fid);

8 fid = fopen('magic3.txt', 'r');

9 fread(fid, [3 3], 'int32'); % try [3 1]?

(16)

Access to Internet

urlread(URL, Name, Value) returns the contents of a URL as a string.

1 contents = urlread('http://www.csie.ntu.edu.tw/...

2 ~d00922011/matlab.html');

3 fid=fopen('matlab.html','w');

4 fprintf(fid,'%s', contents);

5 fclose all;

6 dos('start matlab.html')

Try sendmail, ftp.

(17)

Yahoo Finance API

Current market and historical data from the Yahoo!data server

Blog: 研究雅虎股票API (Yahoo finance stock API) Google: yahoo-finance-managed

Historical Stock Data downloaderby Josiah Renfree (2008)

(18)

Exercise

Suppose that a system of 3 linear equations is stored in a text file.

Write a program that retrieves the coefficients and the constant from the specified text file, such as:

1 3 2 -1 1

2 1 -1 2 -1

3 2 -1 2 0

Call gaussSolver(filename) to solve this system andappend

“The solution is (x , y , z) = . . .” in the original file.

(19)

1 function gaussSolver(str)

2 % main

3 fid=fopen(str,'r');

4 k=1;

5 temp(3,4)=0;

6 while k<4

7 temp(k,:)=str2num(fgetl(fid));

8 k=k+1;

9 end

10 fclose all;

11 A=temp(:,1:3); b=temp(:,4); % init A and b

12 [y s]=gauss(A,b);

13 if s==1 % a flag to tell if succeeded

14 fid=fopen(str,'a');

15 fprintf(fid,'\nThe solution is (%f,%f,%f).',y);

16 fclose all;

17 show=['start ', str];

18 dos(show);

19 disp('Done.')

20 else

(20)

21 disp('Failed in Gauss Elimination.')

22 end

1 function [y s]=gauss(A,b)

2 % s is a flag to indicate the success of Gauss ...

elimination

3 ...

(21)

Exercise

Suppose that the text file contains the following content:

3x + 2y − z = 1 x − y + 2z = −1 2x − y + 2z = 0

In order to organize the coefficient matrix A and constant vector b, we need to separate the numbers from the variables x , y , z and the equality sign =.

(22)

But...

gaussSolver1 cannot deal with the strings like 3x + 2y − 1z = 1.

So, let’s find a way out.

1 function gaussSolver2(str)

2 % main

3 fid=fopen(str,'r');

4 k=1;

5 temp=cell(3,1);

6 while k<4

7 temp{k}=fgetl(fid);

8 k=k+1;

9 end

10 fclose all;

11 [A,b]=init matrix(temp) % deal with the strings

12 [y s]=gauss(A,b);

(23)

13 if s==1 % a flag to tell if succeeded

14 fid=fopen(str,'a');

15 fprintf(fid,'\nThe solution is (%f,%f,%f).',y);

16 fclose all;

17 show=['start ', str];

18 dos(show);

19 disp('Done.')

20 else

21 disp('Failed in Gauss Elimination.')

22 end

(24)

Assume that we are solving a system of linear equations with 3 unknowns and 3constraints.

1 function [A b]=init matrix(temp)

2

3 delete char=['x','y','z','='];

4 A=zeros(3,4);

5 loc=zeros(1,4); % indicators for deleting characters

6 for i=1:3

7 temp conversion=temp{i}; % Notice that temp ...

is a cell array.

8 j=1;

9 k=1;

10 while j<length(temp conversion) && k<5

11 if temp conversion(j)==delete char(k)

12 loc(k)=j;

13 k=k+1;

14 end

15 j=j+1;

end

(25)

17 A(i,:)=[str2num(temp conversion(1:loc(1)-1)),...

18 str2num(temp conversion(loc(1)+1:loc(2)-1)),...

19 str2num(temp conversion(loc(2)+1:loc(3)-1)),...

20 str2num(temp conversion(loc(4)+1:...

21 length(temp conversion)))]

22 end

23 b=A(:,4);

24 A=A(:,1:3);

In the exercise,parsing is a very tedious task.

You can imagine more examples in daily life.

(26)

Code Style

A more clear source code could be like this:

1 function [y s]=gaussSolver3(str,var)

2 % main

3 temp=read(str,var);

4 [A,b]=init matrix(temp)

5 [y s]=gauss(A,b);

6 write(str,y,s);

7 end

8

9 function temp=read(str,var)

10 varnum=length(var);

11 fid=fopen(str,'r');

12 k=1;

13 temp=cell(varnum,1);

14 % while feof(fid)==0

15 while k<varnum+1

temp{k}=fgetl(fid);

(27)

17 k=k+1;

18 end

19 fclose all;

20 end

21

22 function write(str,y,s)

23 if s==1

24 fid=fopen(str,'a');

25 fprintf(fid,'\nThe solution is (');

26 for i=1:length(y)-1

27 fprintf(fid,'%f,',y(i));

28 end

29 fprintf(fid,'%f).',y(length(y)));

30 fclose all;

31 show=['start ', str];

32 dos(show);

33 disp('Done.')

34 else

35 disp('Failed in Gauss Elimination.')

(28)

36 end

37 end

(29)

Exercise (Upgraded)

New features:

1 Able to solve a system of n linear equations.

2 Able to convert x + y − z = 0 to [1 1 − 1 0].

1 function [y s]=gaussSolver4(str,var)

2 % main

3 ...

4 [A,b]=init matrix 1(temp,var)

5 ...

(30)

1 function [A b]=init matrix 1(temp,var)

2 delete char=[var,'='];

3 varnum=length(delete char)-1;

4 A=zeros(varnum,varnum+1);loc(1:varnum+1)=0;

5 for i=1:varnum

6 temp conversion=temp{i};

7 j=1;

8 k=1;

9 while j<length(temp conversion) && k<varnum+2

10 if temp conversion(j)==delete char(k)

11 loc(k)=j;

12 k=k+1;

13 end

14 j=j+1;

15 end

16 %% WARNING

17 for j=1:varnum+1

18 if j==1

19 A(i,j)=str2num(temp conversion(1:loc(j)-1));

20 else if j==varnum+1

(31)

21 A(i,j)=str2num(temp conversion(loc(j)+...

22 1:length(temp conversion)));

23 else

24 A(i,j)=str2num(temp conversion(loc(j-1)+...

25 1:loc(j)-1));

26 end

27 end

28 end

29 %% WARNING

30 end

31 b=A(:,varnum+1);

32 A=A(:,1:varnum);

(32)

Check List

Before the end of this short class, you should check whether or not you have been familiar with:

1 (Problem Formulation) Make a clear definition of problem.

Inputs Outputs

2 (Algorithm)Organize the resource and steps to reach the goal.

3 (Implementation) Implement the algorithm using a programming language, such as MATLAB.

4 (Debugging)There are always bugs in the program. Ready to fight?

5 (Complexity Analysis) Improve the program if the computation cost is unacceptably high.

6 (Generalization) Make your program more flexible.

(33)

Practice Makes Better

Data Structures and Algorithms in C++, Michael T.

Goodrich, Roberto Tamassia, and David M. Mount, 2/e, 2011 Introduction to Algorithms, Thomas H. Cormen, Charles E.

Leiserson, Ronald L. Rivest, and Clifford Stein, 3/e, 2009 高中生程式解題系統

參考文獻

相關文件

9. The IEEE standard only requires that the extended precision format contain more bits than the double precision format... ing very common, it is still possible that you may need

Depending on the specified transfer protocol and data format, this action may return the InstanceID of an AVTransport service that the Control Point can use to control the flow of

The tool to convert user programs from MIPS’s COFF into Nachos’s NOFF format (NOFF: Nachos Object File Format).. Building directories for different

The format of the URI in the first line of the header is not specified. For example, it could be empty, a single slash, if the server is only handling XML-RPC calls. However, if the

• Suppose the input graph contains at least one tour of the cities with a total distance at most B. – Then there is a computation path for

The Matlab fprintf function uses single quotes to define the format string. The fprintf function

[r]

A floating point number in double precision IEEE standard format uses two words (64 bits) to store the number as shown in the following figure.. 1 sign