MATH4602 Tutorial01-MATLAB(1)
MATH4602 Tutorial01-MATLAB(1)
MATH4602
Scientific Computing
Tutorial 1
MATLAB (1)
Download MATLAB
Fundamentals
Polynomials
Graphics
MATH4602 Scientific Computing Tutorial 1
Download MATLAB
In addition, one may use the up and down arrow keys to come
back on previously executed commands.
MATH4602 Scientific Computing Tutorial 1
Fundamentals
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
Syntax functionname(arg)
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
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
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
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
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))
x0=linsolve(A,b)
1. x0 is a particular solution
MATH4602 Scientific Computing Tutorial 1
Fundamentals
Vectors and Matrices
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
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
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
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
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
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
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
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 1
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 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
-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])
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
-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
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
histogram(X,nbins,Name,Value)
or
histogram(X,edges,Name,Value)
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