0% found this document useful (0 votes)
8 views

MATH4602 Tutorial02-MATLAB(2)

This document is a tutorial for MATH4602 Scientific Computing using MATLAB, covering graphics, user-defined functions, conditional statements, loops, and formatted outputs. It provides syntax and examples for plotting graphs, creating functions, and implementing control structures in MATLAB. The tutorial emphasizes the use of various commands and options for effective data visualization and programming practices.

Uploaded by

457 123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

MATH4602 Tutorial02-MATLAB(2)

This document is a tutorial for MATH4602 Scientific Computing using MATLAB, covering graphics, user-defined functions, conditional statements, loops, and formatted outputs. It provides syntax and examples for plotting graphs, creating functions, and implementing control structures in MATLAB. The tutorial emphasizes the use of various commands and options for effective data visualization and programming practices.

Uploaded by

457 123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

MATH4602 Scientific Computing Tutorial 2

MATH4602
Scientific Computing
Tutorial 2
Using MATLAB (2)

Department of Mathematics, HKU


MATH4602 Scientific Computing Tutorial 2
Graphics

MATLAB can plot graphs in a separate figure window.

Before we introduce any plot commands, we introduce the


following

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

Use the command plot to create a 2D line plot of data.

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

▶ All points are 0.4

interpolated linearly 0.2

0
▶ The first curve, y = sinx,
-0.2
is blue by default -0.4

▶ The second curve, -0.6

y = cosx, is red by -0.8

default -1
0 1 2 3 4 5 6 7
MATH4602 Scientific Computing Tutorial 2
Graphics

Although it is possible to fit y1 and y2 into one matrix, it is better to


keep them separate for different styling:

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:

Line Style Marker Color


- solid line (default) o circle r red
-- dashed line + plus g green
: dotted line * asterisk b blue
-. dash-dot line . point y yellow
MATH4602 Scientific Computing Tutorial 2
Graphics

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

▶ The second curve, -0.2

y = cosx, has a blue -0.4

dotted line with points -0.6

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

Below are some line properties that can be altered:

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

command line -0.2

▶ Both curves have a line -0.4

width of 2 and marker -0.6

-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

points along ’steeper’ 0.2

sections of the function 0

so that linear -0.2

interpolation remains -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

One can plot a histogram by using

histogram(X,nbins,Name,Value)
or
histogram(X,edges,Name,Value)

where X is a matrix of data, nbins is the number of bins, and


edges is a vector specifying bin edges.

Name-Value pairs have similar functionality in histogram as


with the plot functions earlier. Some common names include
’BinWidth’, ’EdgeColor’, ’FaceColor’, and
’Normalization’.
MATH4602 Scientific Computing Tutorial 2
Graphics

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

interval [Xmin , Xmax ] is divided into


20 equal parts
pdf of N(0, 1) is plotted for refer-
ence
MATH4602 Scientific Computing 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,...)
MATH4602 Scientific Computing 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).
MATH4602 Scientific Computing Tutorial 2
Simple Programming
User–defined functions

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

The comment preceded by the percentage sign % will not be


interpreted by MATLAB.
MATH4602 Scientific Computing 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.


MATH4602 Scientific Computing Tutorial 2
Simple Programming
Conditioning

Example 7
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
MATH4602 Scientific Computing 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.
MATH4602 Scientific Computing Tutorial 2
Simple Programming
Conditioning

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

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.
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

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


MATH4602 Scientific Computing 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
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

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

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

or

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

▶ formatSpec is the desired format and appears as a row


▶ arg# are quantities (scalar, vector or matrix) to appear
▶ the difference between these commands is that (fprintf)
prints to standard output (command window), whereas
(sprintf) stores data as a string.
MATH4602 Scientific Computing 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

▶ 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)
▶ flag formats text within field width (e.g. ’-’ left aligns the
text)
▶ 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.
MATH4602 Scientific Computing Tutorial 2
Simple Programming
Formatted Outputs

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


decimal places)
▶ TYPE is the data type: d (integer), f (floating point), s
(string), e or E (exponents); every % must end with a data
type
MATH4602 Scientific Computing 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
MATH4602 Scientific Computing Tutorial 2
Simple Programming
Formatted Outputs

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

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

▶ fopen creates/opens the target file filename.dat first and


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

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

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

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

1. Define a MATLAB function p=fixedpt(x0,e), which


gives an approximated value of a fixed point of g when
initial guess x0 and tolerance e are input.
2. Modify the script in (a) so that the whole loop would be
stopped after N iterations, and N should be an extra input of
the function fixedpt.
MATH4602 Scientific Computing Tutorial 2
Exercises

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

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).
MATH4602 Scientific Computing Tutorial 2
Exercises

%the function chooses the interval in bisection

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

%define the function once and for all

function u=f(x)
u=x+exp(x)
end
MATH4602 Scientific Computing 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); 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).


MATH4602 Scientific Computing Tutorial 2
A Quick Summary

About MATLAB

▶ A multi-paradigm numerical computing environment and


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

Get Started with MATLAB

▶ Download and installation.


https://www.mathworks.com/academia/tah-portal/the-
university-of-hong-kong-40755386.html
▶ 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.
▶ Find the use of a function: help function, e.g. help sum.
▶ Find functions that you do not know: search for the keyword
in the search bar to the top right of the window.
▶ Find more information: look up the documentations from
the MATLAB homepage.
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

▶ Common Operators in MATLAB


+ Addition
− Subtraction
∗ Multiplication
/ Division
∧ Power
′ Complex conjugate transpose
▶ Some special constants
i, exp(1), pi, true, false...
▶ Some common functions
sin, cos, tan, abs, min, abs, sqrt, sum...
E.g., sin(1), max([2, 3, abs(−5)])...
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

Strings

▶ 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”.
▶ Concatenating character arrays: use array notation.
E.g., [’This ’,’is ’,’a ’,’character ’,’array.’]
ans=’This is a character array.’
▶ Concatenating strings: use the operator +.
E.g., “This ”+“is ”+“a ”+“string.”
ans=“This is a string.”
▶ 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
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

Numeric Display

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


ans = 1.0000e − 11
▶ When displaying vectors, common factor may be shown
>> x = [1e9 1e11]
x=
1.0e + 11 ∗
0.0100 1.0000
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

Working with matrices

▶ 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

▶ 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
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

Subscripts

▶ The colon operator


▶ Unit step-size
>> 1 : 5
ans = 1 2 3 4 5
▶ Non-unit step-size
>> 10 : −2 : −1
ans = 10 8 6 4 2 0
▶ General form
[Start: Step Size: End]
▶ Basic matrices expressions
▶ A(i, j): the element in the i−th row and j−th column of A.
▶ A(i, :): the i−th row of A.
▶ A(:, j): the j−th column of A.
▶ A(i : j, k ): the i−th to the j−th row of the k −th column of A.
MATH4602 Scientific Computing 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)
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

▶ Entry-wise arithmetic operations


+ Addition
− Subtraction
.∗ Multiplication
.∧ Power
./ Right Devision
▶ Example. Calculate s = 31 + 24 + 35 .
>> A = 1 : 3; B = 3 : 5; C = A./B; sum(C)
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

Solving Linear Systems Ax = b

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


▶ Solution 2: x = A\b
▶ Example. A = rand(3, 3); b = rand(3, 1); x = A\b
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

Polynomials in MATLAB

▶ Polynomials are represented by row vectors. Example:


−4 − 3x + x 2 would be represented as [1 − 3 − 4]
▶ Approach 1. A polynomial p can be represented by the
vector of its coefficients in descending order.
p = [1,-3,-4]
▶ Approach 2. Polynomials can also be constructed by using
the roots.
p = poly([4,-1])
MATH4602 Scientific Computing 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]
▶ >> c = conv (a, b) %polynomial multiplication
▶ >> d = a + b %polynomial addition
▶ Make sure the vector dimensions are the same; put zeros in
front of the shorter vector to match the dimension of the
longer vector.
▶ e.g. [0, 0, 3, 2, 1] + [5, 4, 3, 2, 1]
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

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

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


It returns a column vector with the roots of the polynomial
as its elements.
▶ Value of the polynomial at some number z. Command:
polyval(p,z).
▶ Value of the polynomial evaluated at some matrix z.
Command: polyvalm(p,z).
▶ Calculate the derivative of the polynomial polyder(p).
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

Graphs drawing-2D curves

▶ The plot function:


plot(x, y ) produces graph of y versus x.
Example. Plot the graph of y = x + 2, x ∈ [1, 5].
▶ Solution 1: x = [1 2 3 4 5]; y = x + 2; plot(x, y )
▶ Solution 2: x =linspace(1, 5, 21); y = x + 2; plot(x, y )
▶ To show individual points:
x =linspace(1, 5, 21); y = x + 2; plot(x, y ,′ .′ )
▶ To show points in a curve:
x =linspace(1, 5, 21); y = x + 2; plot(x, y ,′ .−′ )
▶ To show colored points in a curve:
x =linspace(1, 5, 21); y = x + 2; plot(x, y ,′ . − b′ )
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

▶ To plot different sets of data in one window:


x =linspace(1, 5, 21); y = x + 2; z = x − 7
plot(x, y ,′ o′ , x, z,′ s′ )
▶ To add legend:
x =linspace(1, 5, 21); y = x + 2; z = x − 7
plot(x, y ,′ o′ , x, z,′ s′ )
legend(’y = x + 2’, ’z = x − 7’)
▶ To control the size of the axis:
x =linspace(1, 5, 21); y = x + 2; plot(x, y ,′ o′ ),
axis([−1, 5, −1, 8])
▶ To add labels and titles:
x =linspace(1, 5, 21); y = x + 2; plot(x, y ,′ o′ )
xlabel(’x-axis’)
ylabel(’y-axis’)
title(’y = x + 2’)
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

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


and (−1, 2) and mark the vertices with circles.
▶ 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π].


▶ Exercise 3. Draw the ellipse x2 y2
4 + 9 = 1.
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

▶ 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

Graphs drawing-3D Curves

▶ The plot3 function.


plot3(x, y , z) produces the 3D parameterized curve
defined by its coordinates x, y and z.
▶ Example 1. A 3D triangle.
x = [1 0 0 1]; y = [0 1 0 0]; z = [0 0 1 0]; plot3(x, y , z);
▶ Example 2. A 3D helix.
t = linspace(0, 10 ∗ pi); plot3(sin(t), cos(t), t);
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

Graphs drawing-3D Surfaces

▶ The surf function.


surf(x, y , z) produces 3D surfaces.
▶ x=x-coordinates; stored as matrix that is the same size as z
or vector of length n, where [m, n] = size(z);
▶ y=y-coordinates; stored as matrix that is the same size as z
or vector of length m, where [m, n] = size(z);
▶ 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)).
▶ Example.
x = linspace(−4, 4, 21)′ ; y = x ′ ;
z = sin(x) ∗ cos(y );
surf(x, y , z)
MATH4602 Scientific Computing 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.

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


window, or click New Script button from the home bar.
▶ To save the function in a file: click save from the editor bar.
▶ To execute a script: click Run from the menu bar or use the
F5 key.
▶ Procedures of using a function.
Create a function in the editor;
Save the file;
Execute the file;
Use the function in MATLAB.
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

Basic format of a function


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

▶ 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).
▶ out1, out2, out3,. . . are the output variables.
▶ in1, in2, . . . are the input variables.
▶ The calling syntax of the function should be:
[out1, out2, out3,. . . ]=functionname(in1, in2, . . . )
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

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


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

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


one.
x1 = 0, x2 = 1, x2 = 0 + 1 = 2, x3 = 1 + 2 = 3, . . . .
▶ 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
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

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

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.

▶ 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.
▶ Solution.
function y=f(n)
x=3
for k=1:n, x=sqrt(x+1)
end
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.

▶ Basic structure of a while-loop.


while [condition]
[statement]
end
▶ Example. Compute the factorial of 2011 using while-loop.
s=1,k=1
while k <= 2011
s=s*k; k=k+1;
end
MATH4602 Scientific Computing 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
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

▶ Basic structure of the if statement.


if [condition]
[statement]
end
▶ Nested if statement.
if [condition1]
[statement1]
elseif [condition2]
[statement2]
elseif [condition3]
[statement3]
else . . .
end
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

▶ 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
MATH4602 Scientific Computing Tutorial 2
A Quick Summary

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

You might also like