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

MATH4602 Tutorial01-MATLAB(1)

This document is a tutorial for MATLAB, focusing on scientific computing concepts including vectors, matrices, polynomials, and statistics. It provides instructions on downloading MATLAB, basic commands, built-in functions, and examples for practical application. Additionally, it covers graphical plotting techniques and commands for visualizing data.

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

MATH4602 Tutorial01-MATLAB(1)

This document is a tutorial for MATLAB, focusing on scientific computing concepts including vectors, matrices, polynomials, and statistics. It provides instructions on downloading MATLAB, basic commands, built-in functions, and examples for practical application. Additionally, it covers graphical plotting techniques and commands for visualizing data.

Uploaded by

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

MATH4602 Scientific Computing Tutorial 1

MATH4602
Scientific Computing
Tutorial 1
MATLAB (1)

Department of Mathematics, HKU


MATH4602 Scientific Computing Tutorial 1

Download MATLAB

Fundamentals

Vectors and Matrices

Polynomials

Probabilities and Statistics

Graphics
MATH4602 Scientific Computing Tutorial 1
Download MATLAB

MATLAB is a multi-paradigm numerical computing environment;


it is not free, but students can use it under the HKU license.
Sign in with your UID and PIN and follow download instructions
here.
MATH4602 Scientific Computing Tutorial 1
Download MATLAB

The main features of MATLAB are

(a) Command Window (b) Script Editor (c) Figure Window

command window Script Editor


MATH4602 Scientific Computing Tutorial 1
Fundamentals

Just type a command after the prompt >> in the command


window and press the Enter/Return key on the keyboard.

In addition, one may use the up and down arrow keys to come
back on previously executed commands.
MATH4602 Scientific Computing Tutorial 1
Fundamentals

Some basic operations are listed below

Command Descriptions
= assignment
clear, clear var clear or clear var
+, -, *, ˆ addition, subtraction, multiplication, expo-
nent
/, \ division:
√ dividend/divisor, divisor\dividend
pi, exp(1), i, inf π, e, −1 (appears as i) and ∞
true, false logical values true and false
eps the minimum positive quantity recognized by
computer
>, <, >=, <=, ==, ~= comparisons
|, &, ~ logical operations OR, AND, NOT
MATH4602 Scientific Computing Tutorial 1
Fundamentals

Example 1
Try the following commands in MATLAB command window.
1. (2+3)/10 and (2+3)\10
2. 3==2
3. (2<3)&(1+3==4)
4. (2>=3)|(5~=4)
MATH4602 Scientific Computing Tutorial 1
Fundamentals

Below are some common built–in functions

Syntax functionname(arg)

Warning MATLAB is case sensitive

Trigonometric functions sin, cos, tan, asin, acos,


atan
(argument is in radian)
Hyperbolic functions sinh, cosh, tanh
Exponential and Logarithmic exp, log, log10
functions
complex number related real, imag, conj
Rounding up/down/to 0/integer ceil, floor, fix, round
Miscellaneous sqrt, factorial, abs, sign,
max, min
MATH4602 Scientific Computing Tutorial 1
Fundamentals

Example 2
Try the following commands in MATLAB command window.
1. real(2+3*i), imag(2+3*i) and conj(2+3*i)
2. sign(-2) and sign(2)
3. round(pi) and fix(pi)

Remark 1
If a command is ended by a semicolon ;, then the computation
is done but not displayed. Try it with the previous calculations.
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Vectors and Matrices

Matrices are defined by listing entries in square brackets


[ ... ].

▶ space or commas is used to separate columns;


▶ semicolon is used to separate rows.

Example 3
The command >>[2,1,1;3 0 4] produces the following
matrix
2 1 1
.
3 0 4
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Vectors and Matrices

Commands to extract submatrices are listed below. Throughout


A is a pre–defined matrix.

command descriptions
A(i,j) gives aij
A(i,:) gives the i–th row
A(:,j) gives the j–th column
A([1,3],[2,6]) the submatrix which is the intersection
of the 1st and 3rd rows and the 2nd
and 6th columns
A(k) the k –th term in the sequence
a11 , . . . , am1 , a12 , . . . , am2 , . . .
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Vectors and Matrices

Basic matrix operations are

command descriptions
A’ conjugate transpose
A+B, A-B, A*B sum, difference, product
det(A) calculate the determinant of A
inv(A) inverse of A
expm(A) matrix exponent eA
A\B, A/B gives A−1 B and AB −1
A^n n–th power of A
For element wise operations, preceed by a dot
A.*B, A./B element wise product
 and quotient
b
A.^B gives the matrix aij ij
matrix can be argument of a built–in function
 f,
f(A) gives the matrix f (aij )
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Vectors and Matrices

Example 4
Try the following in MATLAB

>> A=[2,1,1;3,0,4];
>> B=[1,-1,2;1/2,1,3];
>> C=[1,3;1,4];
>> A+B
>> A*B
>> A*B’
>> inv(C)
>> C\A
>> sin(A)
>> A.*B
>> A./B
>> A.^B
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Vectors and Matrices

Built–in commands for vectors and matrices are shown below.

Commands Descriptions
length( ) find the length of the vector
size( ) gives a vector m n where m and n are the num-
bers of rows and columns respectively
a:k:b generates a, a + k , . . . ≤ b
linspace(a,b,n) arithmetic sequence of n terms from a to b,
represented as a row vector
zeros(m,n) m × n zero matrix
ones(m,n) m × n all–one matrix
eye(m,n) m × n identity matrix
rand(m,n) m × n uniformly distributed random matrix (val-
ues in [0, 1))
diag( ) generates the diagonal matrix with diagonal
entries listed in the input vector
sum(A(:)) sum of matrix entries
sum(A), sum(A,2) row/col vector of col/row sums
[M,coord]=max(A(:)) M = max entry; coord = location of M
[Mr,coord]=max(A) Mr = row vector of col max; coord = location
vector
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Vectors and Matrices

Example 5
Firstly, create a random 4 × 5 integer matrix by

>> A=fix(10*rand(4,5))

Try the following commands


1. sum(A(:)), sum(A) and sum(A,2)
2. [M,coord]=max(A(:)), [M,coord]=max(A),
[M,coord]=max(A,[],2)
3. mean(A(:)), mean(A) and mean(A,2)
4. prod(A(:)), prod(A) and prod(A,2)
5. [M,coord]=min(A(:)), [M,coord]=min(A),
[M,coord]=min(A,[],2)
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Vectors and Matrices

Let A be an m × n matrix and b be an m–column vector. The


matrix equation Ax = b can be solved by

x0=linsolve(A,b)

It turns out that

1. x0 is a particular solution
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Vectors and Matrices

Let A be a square matrix.

Commands Descriptions
eig(A) gives the vector of eigenvalues of A
[R,D]=eig(A) D is the diagonal matrix of eigenval-
ues and the j–th col of R is a right
eigenvector with associated eigen-
value D(i,i)
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Polynomials

A polynomial
n
X n
Y
p(x) = ai x i = (x − αj )
i=0 j=1

is represented by a row vector containing elements which represent


coefficients ordered by descending powers.

1. p=a, where a is the coefficient vector (an , . . . , a1 ), or


2. p=poly(alpha) where alpha is the roots vector (α1 , . . . , αn ).

Note that the order of elements of a is important.


MATH4602 Scientific Computing Tutorial 1
Fundamentals
Polynomials

Example 6
Define the coefficient vector and roots vector respectively by
--> a=[0,-42,41,-12,1]
--> r=[2,7,0,3]
Try the following commands
1. p=a
2. q=poly(r)
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Polynomials

Remark 2

1. One can also define matrix of polynomials.


2. Basic arithmetic operations are valid for (matrices of)
polynomials in the same indeterminate.
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Polynomials

Some built–in functions for polynomials are listed below

Command Descriptions
roots(p) gives roots vector of p
[Q,R]=deconv(p1,p2) gives the quotient Q and remainder R
when p2 divides p1
polyval(p,a0) evaluate p(a0 )
polyder(p) find derivative of polynomial function
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Probabilities and Statistics

We shall introduce a few MATLAB commands which are


frequently in probabilities and statistics. Some basic distribution
commands for m × n matrices and their parameters are shown
in the next slide.
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Probabilities and Statistics

Commands Descriptions
randi([a,b],m,n) uniformly distributed integers in
[a, b]
binornd(N,p,m,n) binomial distribution
poissrnd(lambda,m,n) Poisson distribution
normrnd(mu,sigma,m,n) normal distribution
chi2rnd(Df,m,n) chi–square distribution
frnd(Dfn,Dfd,m,n) F–distribution
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Probabilities and Statistics

Lastly, we introduce functions for calculating the parameters of the normal


distribution function N(µ, σ):

Commands Descriptions
normcdf(x,mu,sigma) gives P(X ≤ x)
norminv(p,mu,sigma) solves P(X ≤ x) = p for x
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Probabilities and Statistics

Example 7
Consider the standard normal distribution X ∼ N(0, 1).
1. P(X ≤ 0.2) can be evaluated by
>> p=normcdf(0.2,0,1)
2. If P(X ≤ x) = .4, then x can be obtained by
>> p=norminv(0.4,0,1)

Example 8
One may construct a vector of probabilities P(X ≤ xi ) if X ∼ N(µ, σ) as
following.
>> x=linspace(-5,5,11);
>> p=normcdf(x,mu*ones(1,11),sigma*ones(1,11));
>> [x’,p’]
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Probabilities and Statistics

Example 9
Table of inverse distributed function can be obtained as
following.
>> p=linspace(0,1,11);
>> x=norminv(p,mu*ones(1,11),sigma*ones(1,11));
>> [p’,x’]
MATH4602 Scientific Computing Tutorial 1
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 1
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 1
Graphics

Example 10
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 1
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 1
Graphics

Example 11
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 1
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 1
Graphics

Example 12
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 1
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 1
Graphics

Example 13
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 1
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 1
Graphics

Example 14
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

You might also like