MATH3408 Tutorial 2: MATLAB Functions
MATH3408 Tutorial 2: MATLAB Functions
MATH3408
Computational Methods and Differential
Equations with Applications
Tutorial 2
Using MATLAB (2)
Syntax [y1,y2,...]=functionname(x1,x2,...)
>> [y1,y2,...]=functionname(a1,a2,...)
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
User–defined functions
function [var1,var2,...]=functionname(arg1,arg2,...)
instruction1;
instruction2;
instructionk;
var1=expression;
var2=expression; var3=expression
end
Example 1
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 2
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
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Conditioning
switch indicator
case choice1
instruction1
case choice2
instruction2
case choicek
instructionk
otherwise instruction0
end
Example 3
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.
MATH3408 Computational Methods and Differential Equations with Applications 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.
MATH3408 Computational Methods and Differential Equations with Applications 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
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Loops
Example 4
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
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Loops
Example 5
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
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Formatted Outputs
fprintf(formatSpec,arg1,arg2,...)
or
sprintf(formatSpec,arg1,arg2,...)
%[m$][flag][n][.o]TYPE
Example 6
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
MATH3408 Computational Methods and Differential Equations with Applications 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("[Link]",permission)
--> fprintf(var,"formatSpec",arg1,arg2,...)
--> fclose(var)
Example 7
To print the data from bisection method may contain
bisdat=fopen("[Link]","w");
fprintf(bisdat,"%2s %8s %8s %8s %8s\n",’n’,’a’,’c’,’b’,’f(c)’)
while abs(C)>=eps
end
fclose(bisdat)
The file [Link] 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
MATH3408 Computational Methods and Differential Equations with Applications 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.
MATH3408 Computational Methods and Differential Equations with Applications 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?
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Exercises
Exercise 3
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
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Exercises
Exercise 4
Let f (x) = x + ex . Define a function
[anew,bnew]=interval(a,b) which is defined by
I if f (a) and f (c) are of opposite sign, then anew is a and
bnew is c,
I 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.
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Exercises
Exercise 5
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
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Exercises
Exercise 6
Write a script function [x,y]=bisection(a,b,e) to solve
x + ex = 0
function [anew,bnew]=interval(a,b,c)
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
MATH3408 Computational Methods and Differential Equations with Applications 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,c); d=b-a;
end
end
x=c; y=C;
end
About MATLAB
Strings
Numeric Display
I Creating matrices
I separate each elements in a row with a blank space or a
comma;
I separate each row of elements with a semi-colon;
I put the whole list of elements in a pair of square brackets.
I E.g., >> M = [1 2 3; 4 5 6]
M=
1 2 3
4 5 6
MATH3408 Computational Methods and Differential Equations with Applications 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)
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary
Matrices operation
I Matrix inversion
>> inv ([1 2; 1 1])
>> inv ([1 2; 2 4])
I Calculate sums
sum([1, 2; 1, 1], 2)
sum(1 : 2 : 10)
I Diagonal elements
diag([1, 2; 1, 1])
I Eigenvalue and eigenvectors
eig(A), it shows all the eigenvalues of the matrix in a
vector.
[R, diagevals] = eig(A)
MATH3408 Computational Methods and Differential Equations with Applications 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.
I Solution to exercise 1.
x = [0 2 − 1 0], y = [−1 3 2 − 1], plot (x,y,’-o’)
I Solution to exercise 2. t = linspace(0, 2 ∗ pi); x = sin(t);
y = cos(t); plot(x, y ).
I 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 ).
MATH3408 Computational Methods and Differential Equations with Applications 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.
I Solution 1.
s=0;
for k=1:2011, s=s+k
end
I Solution 2.
s=zeros(1,2011);
for i=1:2011, s(i)=i;
end
s=sum(s)
MATH3408 Computational Methods and Differential Equations with Applications 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.
I 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);