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.
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.
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?
Escape Characters
%%: Percent character
\\: Backslash
\b: Backspace
\n: New line
\t: Horizontal tab
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.
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);
1 >> grep('grep.m','matched')
2
3 6: matched=findstr(line, pattern);
4 7: if ~isempty (matched) % tell if matched is ...
empty array
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
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’).
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.
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);
1 >>
2
3 A =
4
5 78
6 72
7 64
8 66
9 49
10 11
12 count =
13
14 5
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.
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.
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]?
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.
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)
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.
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
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 ...
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 =.
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);
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
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
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.
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);
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.')
36 end
37 end
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 ...
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
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);
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.
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 高中生程式解題系統