0% found this document useful (0 votes)
11 views60 pages

MATH3408 Tutorial 2: MATLAB Functions

This document is a tutorial for MATH3408, focusing on computational methods and differential equations using MATLAB. It covers user-defined functions, conditional statements, loops, formatted outputs, and includes several programming examples and exercises. The tutorial aims to enhance understanding of MATLAB programming concepts relevant to the course.

Uploaded by

yandeqi79
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views60 pages

MATH3408 Tutorial 2: MATLAB Functions

This document is a tutorial for MATH3408, focusing on computational methods and differential equations using MATLAB. It covers user-defined functions, conditional statements, loops, formatted outputs, and includes several programming examples and exercises. The tutorial aims to enhance understanding of MATLAB programming concepts relevant to the course.

Uploaded by

yandeqi79
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2

MATH3408
Computational Methods and Differential
Equations with Applications
Tutorial 2
Using MATLAB (2)

Department of Mathematics, HKU


MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
User–defined functions

A function must be defined in the script editor, and saved as a


*.m file.

Functions have the following syntax:

Syntax [y1,y2,...]=functionname(x1,x2,...)

[y1,y2,...] is the vector of outputs.

x1 etc are inputs.

To execute the function, the following should be typed in the


command prompt

>> [y1,y2,...]=functionname(a1,a2,...)
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
User–defined functions

Functions must be defined within the function ... end


environment.

function [var1,var2,...]=functionname(arg1,arg2,...)
instruction1;
instruction2;
instructionk;
var1=expression;
var2=expression; var3=expression
end

Note that arg# can be another function–name (need not to include


the brackets and arguments).

It’s suggested to enter each instruction on a separate line. In case


that it’s necessary to type multiple statements on the same line,
separate each statement by a semicolon (semicolons also suppress
printing).
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
User–defined functions

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

The comment preceded by the percentage sign % will not be


interpreted by MATLAB.
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Conditioning

There are two conditional statements. The first one is if ... then
and its variants.

There are three major forms

1. if .. end;
2. if .. else .. end;
3. if .. elseif .. else .. end.

There is no restriction on the number of elseif branches.


MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Conditioning

Example 2
Let’s define the case–defined function:

f (x) = x 2 χ(−∞,−1] + (4x − 3)χ(−1,1) + 3χ[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
Simple Programming
Conditioning

If the conditional statement depends on which value (from of a finite


set of choices) an indicator takes, then one may use the
switch .. end command.

switch indicator
case choice1
instruction1
case choice2
instruction2
case choicek
instructionk
otherwise instruction0
end

Important Note that each case checks whether the indicator is


equal to the choice.
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Conditioning

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

Two commonly used lists are m:n and m:k:n.

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

As long as the condition is true, the iteration will be continued.


MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Loops

The following are some tools which may be useful when


defining a loop and debugging.

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

We can format the output to the command window by the commands

fprintf(formatSpec,arg1,arg2,...)

or

sprintf(formatSpec,arg1,arg2,...)

I formatSpec is the desired format and appears as a row


I arg# are quantities (scalar, vector or matrix) to appear
I the difference between these commands is that (fprintf)
prints to standard output (command window), whereas
(sprintf) stores data as a string.
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Formatted Outputs

The formatSpec contains formatting operators which affect


the format of the output fields from other input arguments.

Formatting operators take the form

%[m$][flag][n][.o]TYPE

I m$ is the identifier: 1$ calls arg1, 2$ calls arg2, etc. (by


default, the 1st % refers to arg1, the 2nd % refers to arg2,
etc. so an identifier is not necessary)
I flag formats text within field width (e.g. ’-’ left aligns the
text)
I n is the field width, the minimum number of characters that
the text will occupy; if text is shorter than field width,
remaining spaces will be filled with white space.
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Formatted Outputs

I .o is the precision of the value (e.g. ’.3’ indicates 3


decimal places)
I TYPE is the data type: d (integer), f (floating point), s
(string), e or E (exponents); every % must end with a data
type
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Formatted Outputs

Besides the formatting operators, formatSpec may contain


some escape characters which indicate actions in the printing
of a format string.

Escape characters start with backslash \

Escape char Action


\n create a new line
\t move to the next horizontal tab
\v move to the next vertical tab
\b back one space
\a sounds the computer bell
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Formatted Outputs

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

fprintf("%2d %8.6f %8.6f %8.6f %8.6e\n",n,a,c,b,f(c))

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)

I fopen creates/opens the target file [Link] first and


assign it to the variable var for later reference.
I permission determines how the file should be opened. "r"
opens files for reading, "w" creates/opens files for writing.
I fprintf is essentially the same as the two output commands
except that it has one more argument – the target file
I the whole action is closed by fclose
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Simple Programming
Formatted Outputs

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

fprintf(bisdat,"%2d %8.6f %8.6f %8.6f %8.6e\n",n,a,c,b,f(c))

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

by the method of bisection. Here, [a, b] is the initial interval. This


function should be able to do the following:
1. Stop whenever f (a) or f (b) is zero; and the message
a is a zero and b is a zero should be displayed
accordingly. The exact value of a or b is not required in this
message.
2. Stop whenever f (c) = 0; and x = c and y = f (c).
3. Stop whenever whenever |b − a| < e; and x = c and y = f (c).
Test your program with (a, b, e) = (−1, 0, 0.000001).
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Exercises

%the function chooses the interval in bisection

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

%define the function once and for all

function u=f(x)
u=x+exp(x);
end
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
Exercises

Bisection method below calls the sub–program interval.

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

If (a, b, e) = (−1, 0, 0.000001), then (x, y ) = (−0.5671434, −0.0000002).


MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

About MATLAB

I A multi-paradigm numerical computing environment and


proprietary programming language.
I Widely applicable.
In this course: solving ordinary differential equations
(ODEs) and partial differential equations (PDEs);
Also: signal processing, statistical analysis, numerical
optimization...
I Allows users to create their own functions and libraries.
I Powerful visualizations and graphics.
I Main data type: matrices.
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

Get Started with MATLAB

I Download and installation.


[Link]
[Link]
I Basic windows.
Command Window: type in commands directly.
Editor: manage several files at the same time.
Figure Window: get visualizations.
Help browser: obtain help information.
I Find the use of a function: help function, e.g. help sum.
I Find functions that you do not know: search for the keyword
in the search bar to the top right of the window.
I Find more information: look up the documentations from
the MATLAB homepage.
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

I Common Operators in MATLAB


+ Addition
− Subtraction
∗ Multiplication
/ Division
∧ Power
0 Complex conjugate transpose
I Some special constants
i, exp(1), pi, true, false...
I Some common functions
sin, cos, tan, abs, min, abs, sqrt, sum...
E.g., sin(1), max([2, 3, abs(−5)])...
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

Strings

I Entering strings: character arrays are enclosed with


single quotations; strings are enclosed with double
quotations. They are similar, but not the same.
E.g., ’This is a character array’ and “This is a string”.
I Concatenating character arrays: use array notation.
E.g., [’This ’,’is ’,’a ’,’character ’,’array.’]
ans=’This is a character array.’
I Concatenating strings: use the operator +.
E.g., “This ”+“is ”+“a ”+“string.”
ans=“This is a string.”
I Showing text: use the fprintf function.
E.g., fprintf(’This is a sentence: %d multiplied by %.2f
equals %d’,2,3,6)
%d: signed decimal integer; %f decimal floating point
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

Numeric Display

I In MATLAB, the number 1 × 10−11 is displayed as


ans = 1.0000e − 11
I When displaying vectors, common factor may be shown
>> x = [1e9 1e11]
x=
1.0e + 11 ∗
0.0100 1.0000
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

Working with matrices

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

I Expanding the matrices


We can assign value to out-of-bound elements of a matrix,
and MATLAB will automatically fill in 0s to make it a
valid-size matrix. Example:
>> M = [1 2 3; 4 5 6]; M(3, 1) = 10
M=
1 2 3
4 5 6
10 0 0
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

Subscripts

I The colon operator


I Unit step-size
>> 1 : 5
ans = 1 2 3 4 5
I Non-unit step-size
>> 10 : −2 : −1
ans = 10 8 6 4 2 0
I General form
[Start: Step Size: End]
I Basic matrices expressions
I A(i, j): the element in the i−th row and j−th column of A.
I A(i, :): the i−th row of A.
I A(:, j): the j−th column of A.
I A(i : j, k ): the i−th to the j−th row of the k −th column of A.
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

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

I Entry-wise arithmetic operations


+ Addition
− Subtraction
.∗ Multiplication
.∧ Power
./ Right Devision
I Example. Calculate s = 31 + 24 + 35 .
>> A = 1 : 3; B = 3 : 5; C = A./B; sum(C)
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

Solving Linear Systems Ax = b

I Solution 1: x = inv (A) ∗ b


I Solution 2: x = A\b
I Example. A = rand(3, 3); b = rand(3, 1); x = A\b
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

Polynomials in MATLAB

I Polynomials are represented by row vectors. Example:


−4 − 3x + x 2 would be represented as [1 − 3 − 4]
I Approach 1. A polynomial p can be represented by the
vector of its coefficients in descending order.
p = [1,-3,-4]
I Approach 2. Polynomials can also be constructed by using
the roots.
p = poly([4,-1])
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

The first approach to built a polynomial by the means of vector


is preferred, because it facilitates some polynomial operations.
Below are some examples.
>> a = [1, 2, 3]
>> b = [2, 1, 3]
I >> c = conv (a, b) %polynomial multiplication
I >> d = a + b %polynomial addition
I Make sure the vector dimensions are the same; put zeros in
front of the shorter vector to match the dimension of the
longer vector.
I e.g. [0, 0, 3, 2, 1] + [5, 4, 3, 2, 1]
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

More on polynomial
MATLAB has many handy built-in functions for polynomials.
Assume that we have a polynomial p.

I Find the root of a polynomial. Command: z=roots(p).


It returns a column vector with the roots of the polynomial
as its elements.
I Value of the polynomial at some number z. Command:
polyval(p,z).
I Value of the polynomial evaluated at some matrix z.
Command: polyvalm(p,z).
I Calculate the derivative of the polynomial polyder(p).
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

Graphs drawing-2D curves

I The plot function:


plot(x, y ) produces graph of y versus x.
Example. Plot the graph of y = x + 2, x ∈ [1, 5].
I Solution 1: x = [1 2 3 4 5]; y = x + 2; plot(x, y )
I Solution 2: x =linspace(1, 5, 21); y = x + 2; plot(x, y )
I To show individual points:
x =linspace(1, 5, 21); y = x + 2; plot(x, y ,0 .0 )
I To show points in a curve:
x =linspace(1, 5, 21); y = x + 2; plot(x, y ,0 .−0 )
I To show colored points in a curve:
x =linspace(1, 5, 21); y = x + 2; plot(x, y ,0 . − b0 )
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

I To plot different sets of data in one window:


x =linspace(1, 5, 21); y = x + 2; z = x − 7
plot(x, y ,0 o0 , x, z,0 s0 )
I To add legend:
x =linspace(1, 5, 21); y = x + 2; z = x − 7
plot(x, y ,0 o0 , x, z,0 s0 )
legend(’y = x + 2’, ’z = x − 7’)
I To control the size of the axis:
x =linspace(1, 5, 21); y = x + 2; plot(x, y ,0 o0 ),
axis([−1, 5, −1, 8])
I To add labels and titles:
x =linspace(1, 5, 21); y = x + 2; plot(x, y ,0 o0 )
xlabel(’x-axis’)
ylabel(’y-axis’)
title(’y = x + 2’)
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

I Exercise 1. Draw the triangle with vertices (0, −1), (2, 3)


and (−1, 2) and mark the vertices with circles.
I Exercise 2. Draw a unit circle (A circle centered at the
origin with radius 1).
Hints: A circle can be represented by

x = sin(t)
y = cos(t)

with t ∈ [0, 2π].


I Exercise 3. Draw the ellipse x2 y2
4 + 9 = 1.
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

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

Graphs drawing-3D Curves

I The plot3 function.


plot3(x, y , z) produces the 3D parameterized curve
defined by its coordinates x, y and z.
I Example 1. A 3D triangle.
x = [1 0 0 1]; y = [0 1 0 0]; z = [0 0 1 0]; plot3(x, y , z);
I Example 2. A 3D helix.
t = linspace(0, 10 ∗ pi); plot3(sin(t), cos(t), t);
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

Graphs drawing-3D Surfaces

I The surf function.


surf(x, y , z) produces 3D surfaces.
I x=x-coordinates; stored as matrix that is the same size as z
or vector of length n, where [m, n] = size(z);
I y=y-coordinates; stored as matrix that is the same size as z
or vector of length m, where [m, n] = size(z);
I z=z-coordinates; stored as matrix of size m × n and z(i, j) is
the value (height) of the surface at the point (x(i), y (j)).
I Example.
x = linspace(−4, 4, 21)0 ; y = x 0 ;
z = sin(x) ∗ cos(y );
surf(x, y , z)
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

User defined functions


Except for the built-in functions such as sin() and cos(),
MATLAB has an open programming environment that allows
users to create their own functions and libraries. It is done by
using the built-in editor.

I To open an editor window: type edit() in the command


window, or click New Script button from the home bar.
I To save the function in a file: click save from the editor bar.
I To execute a script: click Run from the menu bar or use the
F5 key.
I Procedures of using a function.
Create a function in the editor;
Save the file;
Execute the file;
Use the function in MATLAB.
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

Basic format of a function


All functions begin with the line
function [out1, out2, out3,. . . ]=ftnname(in1, in2,. . . )

I ftnname is the name of the function. Usually it should be


descriptive and not to be duplicated with the built-in
function names in MATLAB (such as sum, max, etc).
I out1, out2, out3,. . . are the output variables.
I in1, in2, . . . are the input variables.
I The calling syntax of the function should be:
[out1, out2, out3,. . . ]=functionname(in1, in2, . . . )
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

I Example. Create a function distance(x, y ) to calculate the


distance of he point (x, y ) from the origin.
I To create the function:
function d=distance(x, y )
d=sqrt(x 2 + y 2 )
end
I To use the function:
h=distance(1, 2)
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).

I Brute-force approach: we calculate the elements one by


one.
x1 = 0, x2 = 1, x2 = 0 + 1 = 2, x3 = 1 + 2 = 3, . . . .
I For-loop approach: actually, we repeatedly sum the last
two elements to get the new one for 10 times.
The for-loop function for this problem in MATLAB is:
x(1)=0; x(2)=1;
for k=1:10, x(k+2)=x(k+1)+x(k); end, x
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

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

Use for-loop to find the approximation of the limit of a


convergent sequence
If we want to find
pthe limit of the following convergent sequence.
x1 = 3, xk +1 = (xk + 1) for ∀k ≥ 1.

I Discussion. For a convergent sequence, xk gets close to


the limit if k is large enough, hence the approximation of
the limit can be found by calculating xk with very large k .
We can write a function for it by applying for-loop.
I Solution.
function y=f(n)
x=3
for k=1:n, x=sqrt(x+1)
end
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.

I Basic structure of a while-loop.


while [condition]
[statement]
end
I Example. Compute the factorial of 2011 using while-loop.
s=1,k=1
while k <= 2011
s=s*k; k=k+1;
end
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

if, else, elseif


Logical expressions in MATLAB:
== equal
∼= not equal
>= greater than or equal to
<= less than or equal to
> greater than
< less than
∼ not

Expressions for logical comparisons in Scilab:


& and
| or
∼ not
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

I Basic structure of the if statement.


if [condition]
[statement]
end
I Nested if statement.
if [condition1]
[statement1]
elseif [condition2]
[statement2]
elseif [condition3]
[statement3]
else . . .
end
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

I Example. To classify the number input by user.


s=input(’Please input a number’)
if s > 0
disp(’It is positive.’)
elseif s < 0
disp(’It is negative.’)
else
disp(’It is neither positive or negative.’)
end
MATH3408 Computational Methods and Differential Equations with Applications Tutorial 2
A Quick Summary

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

You might also like