MATH4602 Tutorial02-MATLAB(2)
MATH4602 Tutorial02-MATLAB(2)
MATH4602
Scientific Computing
Tutorial 2
Using MATLAB (2)
Command Description
figure open a new figure window
figure(n) set the current figure to be the n–th one
clf clear the figure
clf(n) clear the n–th figure
MATH4602 Scientific Computing Tutorial 2
Graphics
Syntax plot(X,Y,LineSpec,Name,Value)
Arguments Description
X vector or matrix of x-coordinates
Y vector or matrix of y-coordinates; must be equal to size
of X
LineSpec specifies line style, marker symbol, and line color.
Name,Value Name-Value pair that specifies line properties glob-
ally (similar functionality to LineSpec). For example,
’Color’,’red’ specifies line with red color.
When X and Y are m × n matrix, plot(X,Y) gives n curves: the j–th column
of X couples with the j–th column of Y and form a curve. However, X can
simply be an m–vector and again n curves will be plotted – each correspond
to a column of Y with the same X–inputs and vice versa.
MATH4602 Scientific Computing Tutorial 2
Graphics
Example 1
Below is an example of plotting y1 = sin(x) and y2 = cos(x):
>> X=linspace(0,2*pi,20)’; %column vector
>> Y1=sin(X); Y2=cos(X);
>> Y=[Y1,Y2]; %matrix
>> plot(X,Y)
1
▶ 2 curves y = sinx and
0.8
y = cosx are plotted 0.6
0
▶ The first curve, y = sinx,
-0.2
is blue by default -0.4
default -1
0 1 2 3 4 5 6 7
MATH4602 Scientific Computing Tutorial 2
Graphics
plot(X,Y1[,LineSpec1],X,Y2[,LineSpec2])
After each x,y-pair, one can put an optional string indicating the
LineSpec. Below are some specifiers:
Example 2
Below is an example of plotting y1 = sin(x) and y2 = cos(x) with
LineSpec:
>> X=linspace(0,2*pi,20); %row vector
>> Y1=sin(X); Y2=cos(X);
>> plot(X,Y1,’--or’,X,Y2,’:.b’)
0.8
0.6
▶ The first curve, y = sinx,
0.4
has a red dashed line 0.2
with circle markers 0
-0.8
-1
0 1 2 3 4 5 6 7
MATH4602 Scientific Computing Tutorial 2
Graphics
We can also apply universal styling using Name-Value pairs at the end of all
x,y-pairs:
plot(X,Y1[,LineSpec1],X,Y2[,LineSpec2][,Name,Value])
Name Description
’Color’ specifies line color of the plots; values can be RGB
Triplets (e.g. [1 0 0]), Hexadecimal Color Codes
(e.g. ’#FF0000’), or common color names (e.g.
’r’).
’LineStyle’ specifies line style; e.g. ’--’ indicates dashed lines.
’LineWidth’ specifies line width; 0.5 is the default line width.
’Marker’ specifies marker symbol; e.g. ’o’ indicates circle
markers.
’MarkerSize’ specifies marker size; 6 is the default marker size.
MATH4602 Scientific Computing Tutorial 2
Graphics
Example 3
Below is an example of plotting y1 = sin(x) and y2 = cos(x) with
LineSpec and some Name-Value pairs:
>> X=linspace(0,2*pi,20); %row vector
>> Y1=sin(X); Y2=cos(X);
>> plot(X,Y1,’--or’,X,Y2,’:.b’,...
’LineWidth’,2,’MarkerSize’,10)
0.8
▶ The parenthesis in the
0.6
third command line 0.4
indicates the expression 0.2
is continued in the next 0
-0.8
size of 10
-1
0 1 2 3 4 5 6 7
MATH4602 Scientific Computing Tutorial 2
Graphics
The plot function is more useful for visualizing discrete data sets and
differential equations solved numerically. To plot functions with expressions,
use the command fplot. The fplot function is better at choosing points for
drawing functions.
Syntax fplot(f,xinterval,LineSpec,Name,Value)
Arguments Description
f function to plot; must be a function handle. For ex-
ample, f (x) = sin(x) would be declared like so:
f = @(x) sin(x)
xinterval specified interval for x; must be 1 × 2 column vector. It
is [-5 5] by default.
LineSpec specifies line style, marker symbol, and line color.
Name,Value Name-Value pair that specifies line properties.
To put multiple functions in the same plot, use hold on. After putting
enough functions in the plot, use hold off.
MATH4602 Scientific Computing Tutorial 2
Graphics
Example 4
Below is an example of plotting f1 = sin(x 2 ) and f2 = cos(x 2 ) in
0 ≤ x ≤ 5 on the same plot:
>> f1=@(x) sin(x^2); f2=@(x) cos(x^2);
>> fplot(f1,[0,5],’--b’)
>> hold on
>> fplot(f2,[0,5],’-.r’)
>> hold off
0.8
0.6
▶ fplot chooses closer 0.4
accurate -0.6
-0.8
-1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
MATH4602 Scientific Computing Tutorial 2
Graphics
histogram(X,nbins,Name,Value)
or
histogram(X,edges,Name,Value)
Example 5
Let’s plot the histogram of 1000 random numbers which follow standardized
normal distribution.
>> X=normrnd(0,1,1,1000);
>> histogram(X,20,’Normalization’,’pdf’)
>> hold on
>> f=@(x) exp(-x^2/2)/sqrt(2*pi);
>> fplot(f,[-4,4],’LineWidth’,2)
>> hold off
Syntax [y1,y2,...]=functionname(x1,x2,...)
>> [y1,y2,...]=functionname(a1,a2,...)
MATH4602 Scientific Computing Tutorial 2
Simple Programming
User–defined functions
function [var1,var2,...]=functionname(arg1,arg2,...)
instruction1;
instruction2;
instructionk;
var1=expression;
var2=expression; var3=expression
end
Example 6
Let’s define Heron’s formula.
function y=heron(a,b,c)
%define the heron’s formula
s=(a+b+c)/2;
y=sqrt(s*(s-a)*(s-b)*(s-c));
end
There are two conditional statements. The first one is if ... then
and its variants.
1. if .. end;
2. if .. else .. end;
3. if .. elseif .. else .. end.
Example 7
Let’s define the case–defined function:
function y=f(x)
if x<=-1
y=x^2;
elseif x<1
y=4*x-3;
else y=3;
end
end
MATH4602 Scientific Computing Tutorial 2
Simple Programming
Conditioning
switch indicator
case choice1
instruction1
case choice2
instruction2
case choicek
instructionk
otherwise instruction0
end
Example 8
Write a MATLAB script to flip a coin.
function flipacoin()
disp(’flip a coin and get’);
ncoin=randi([0,1]);
switch ncoin
case 0
disp(’Head’);
case 1
disp(’Tail’);
end
end
Note that there is no input argument and output variable.
MATH4602 Scientific Computing Tutorial 2
Simple Programming
Loops
There are two iteration structures in MATLAB: the for loop and the
while loop. We start with the for loop.
for counter=list
instruction1
instruction2
...
instructionk
end
counter will take values from the 1st element in the list to the last
one; and the instructions are executed once for each value in the
list.
MATH4602 Scientific Computing Tutorial 2
Simple Programming
Loops
If the number of iteration is not known in advance, then one may use
the while loop.
while condition
instruction1
instruction2
...
instructionk
end
Commands Descriptions
disp(var) displays the value of the variable
pause stop the loop and continue by pressing
any key
continue stop a particular iteration and move to
the next one
break abandon the whole loop
return exits the function
MATH4602 Scientific Computing Tutorial 2
Simple Programming
Loops
Example 9
We define a function to check whether a given positive integer is prime or not.
function v=isprime(n) %check if n is prime
stop=floor(sqrt(n)); %need to check numbers <= n^{1/2}
v=true;
for i=2:stop
if mod(n,i)==0
fprintf(’a factor is %d\n’, i);
v=false;
break;
end
end
end
MATH4602 Scientific Computing Tutorial 2
Simple Programming
Loops
Example 10
We define another function to check whether a given positive integer is prime
or not.
function v=isprime2(n) %check if n is prime
if mod(n,2)==0
fprintf(’%d is even\n’, n); v=false; return
end %the whole function is aborted if p is even
stop=floor(sqrt(n)); %need to check numbers <= n^{1/2}
v=true; divisor=3;
while (divisor<=stop)&(v==true)
if mod(n,divisor)==0
fprintf(’a factor is %d\n’, divisor);
v=false;
else divisor=divisor+2;
end
end
end
MATH4602 Scientific Computing Tutorial 2
Simple Programming
Formatted Outputs
fprintf(formatSpec,arg1,arg2,...)
or
sprintf(formatSpec,arg1,arg2,...)
%[m$][flag][n][.o]TYPE
Example 11
The following command lines may appear in a script for bisection method
fprintf("%2s %8s %8s %8s %8s\n",’n’,’a’,’c’,’b’,’f(c)’)
while abs(C)>=eps
end
A snapshot of the output may be
n a c b f(c)
0 -4.000000 -3.500000 -3.000000 3.205858e-01
1 -3.500000 -3.250000 -3.000000 6.942093e-02
MATH4602 Scientific Computing Tutorial 2
Simple Programming
Formatted Outputs
One can also print the output to a file by the command fprintf
which must be accomplished by two other commands.
--> var=fopen("filename.txt",permission)
--> fprintf(var,"formatSpec",arg1,arg2,...)
--> fclose(var)
Example 12
To print the data from bisection method may contain
bisdat=fopen("EgBisec.txt","w");
fprintf(bisdat,"%2s %8s %8s %8s %8s\n",’n’,’a’,’c’,’b’,’f(c)’)
while abs(C)>=eps
end
fclose(bisdat)
The file EgBisec.txt will contain
n a c b f(c)
0 -4.000000 -3.500000 -3.000000 3.205858e-01
1 -3.500000 -3.250000 -3.000000 6.942093e-02
MATH4602 Scientific Computing Tutorial 2
Exercises
Exercise 1
We compute the sum of consecutive integers 1, 2, . . . , 10.
sum=0 %assign the initial value
for i=1:10
sum=sum+i
end
MATLAB will ignore everything after % and thus one can add
explanation to command lines.
MATH4602 Scientific Computing Tutorial 2
Exercises
Exercise 2
We write a script to find the remainder when 1322 is divided by
17 by using subtraction. Write the following command lines in
the script editor.
r=1322; d=17;
while r>=d
r=r-d;
end
The iteration stops whenever r is less than d.
Copy and paste the script into the command window and
execute. What is the remainder?
MATH4602 Scientific Computing Tutorial 2
Exercises
Exercise 3
Consider the equation: 2x − tan x = 0.
Note that solutions of the equation are exactly fixed points of
1 π π
g(x) = tan x, − <x < .
2 2 2
Exercise 4
Consider the case–defined function
2
x if x ≤ −1
f (x) = 4x − 3 if −1 < x < 1
3 if x ≥ 1.
function y=f(x)
if x<=-1
y=x^2;
elseif x<1
y=4*x-3;
else y=3;
end
end
MATH4602 Scientific Computing Tutorial 2
Exercises
Exercise 5
Let f (x) = x + ex . Define a function
[anew,bnew]=interval(a,b) which is defined by
▶ if f (a) and f (c) are of opposite sign, then anew is a and
bnew is c,
▶ if f (c) and f (b) are of opposite sign, then anew is c and
bnew is b
where c = (a + b)/2 is the midpoint. You may assume the
inputs are carefully chosen so that these are the only cases.
Test your program with (a, b) = (−1, 0) and reiterate with the
outputs.
MATH4602 Scientific Computing Tutorial 2
Exercises
Exercise 6
It’s known that every positive integer n can be factorized into
n = 2k m where m is odd. In order to find m, two programs are
proposed. Compare their outputs.
1. x=3840;
while x>0
x=x/2
end
2. x=3840;
while x>0
x=x/2
if x-fix(x)>0
return
end
end
MATH4602 Scientific Computing Tutorial 2
Exercises
Exercise 7
Write a script function [x,y]=bisection(a,b,e) to solve
x + ex = 0
function [anew,bnew]=interval(a,b)
if f(a)*f(c)<0
anew=a; bnew=c;
elseif f(c)*f(b)<0
anew=c; bnew=b;
end
end
function u=f(x)
u=x+exp(x)
end
MATH4602 Scientific Computing Tutorial 2
Exercises
function [x,y]=bisection(a,b,e)
d=b-a;
while d>=e
A=f(a); B=f(b);
if A==0
x=a; return
elseif B==0
x=b; return
end
if A*B>0
disp("Same Sign"); return
end
c=(b+a)/2; C=f(c);
if C==0
x=c; return
else [a,b]=interval(a,b); d=b-a;
end
end
x=c; y=C;
end
About MATLAB
Strings
Numeric Display
▶ Creating matrices
▶ separate each elements in a row with a blank space or a
comma;
▶ separate each row of elements with a semi-colon;
▶ put the whole list of elements in a pair of square brackets.
▶ E.g., >> M = [1 2 3; 4 5 6]
M=
1 2 3
4 5 6
MATH4602 Scientific Computing Tutorial 2
A Quick Summary
Subscripts
Special matrices
zeros all zeros
ones all ones
eye identity matrix (all diagonal elements are 1 and all oth-
ers are 0)
rand uniformly distributed random elements
Examples:
>> zeros(2, 3)
>> 8 ∗ ones(2, 2)
>> eye(4, 5)
>> rand(2, 3)
MATH4602 Scientific Computing Tutorial 2
A Quick Summary
Matrices operation
▶ Matrix inversion
>> inv ([1 2; 1 1])
>> inv ([1 2; 2 4])
▶ Calculate sums
sum([1, 2; 1, 1], 2)
sum(1 : 2 : 10)
▶ Diagonal elements
diag([1, 2; 1, 1])
▶ Eigenvalue and eigenvectors
eig(A), it shows all the eigenvalues of the matrix in a
vector.
[R, diagevals] = eig(A)
MATH4602 Scientific Computing Tutorial 2
A Quick Summary
Polynomials in MATLAB
More on polynomial
MATLAB has many handy built-in functions for polynomials.
Assume that we have a polynomial p.
▶ Solution to exercise 1.
x = [0 2 − 1 0], y = [−1 3 2 − 1], plot (x,y,’-o’)
▶ Solution to exercise 2. t = linspace(0, 2 ∗ pi); x = sin(t);
y = cos(t); plot(x, y ).
▶ Solution to exercise 3. Since the ellipse can be
represented by
x = 2 ∗ sin(t)
y = 3 ∗ cos(t)
t=linspace(0, 2*pi); x = 2 ∗ sin(t); y = 3 ∗ cos(t); plot(x, y ).
MATH4602 Scientific Computing Tutorial 2
A Quick Summary
The For-Loop
Sometimes, we need to carry out a similar operation repeatedly,
this will be more conveniently accomplished by the for-loop.
For example, we want to see the first 12 elements of the
sequence defined as follows:
x0 = 1,x1 = 1 xk +2 = xk +1 + xk for all k ≥ 1 (Fibonacci
Sequence).
Basic structure
for variable=i:step:j
[statement]
end
Another example
Compute the sum of 1 to 2011.
▶ Solution 1.
s=0;
for k=1:2011, s=s+k
end
▶ Solution 2.
s=zeros(1,2011);
for i=1:2011, s(i)=i;
end
s=sum(s)
MATH4602 Scientific Computing Tutorial 2
A Quick Summary
The While-Loop
The while-loop repeats the operations as long as the condition
statement is true.
break, continue
The break command: to end a loop.
The continue command: to immediately start the next iteration.
▶ Example. The user is asked to input 10 numbers, and we are going to
calculate all the integers, but this program will be terminated once the
user enters a negative number.
result=0;
for i=1:10;
tem =input(’Please input a number’);
if tem < 0
break;
end
if tem ∼= int(tem)
continue;
end
result=result+tem;
end
display(result);