Lab 3: MATLAB Tutorial
Zhuo Wang
Department of Bioinformatics & Biostatistics
Shanghai Jiao Tong University
(Parts of slides are from Maoying Wu)
MATLAB: Functions
Matrix manipulations
Visualization of data
Implementation of algorithms
Creation of user interfaces
Maoying Wu SysBio
MATLAB: Layouts
Current Folder
Editor
Command Window
Workspace
Command History
Maoying Wu SysBio
Using help or doc
help
help command
help on toolbar
doc command
doc query
Maoying Wu SysBio
Matlab classes: primitives
The three main classes in Matlab are
double: multidimensional array of double precision floating
point numbers
char: multidimensional array of ascii characters
logical: Multidimensional array of 1-bit (0/1) numbers
Eight other built-in primitive classes are
uint8, uint16, uint32, uint64: multidimensional array of 8,
16, 32 or 64-bit, unsigned integers
int8, int16, int32, int64: multidimensional array of 8, 16, 32
or 64-bit, signed integers
Every object in Matlab is a rectangular array, and arrays are at
least 2-dimensional (no notion of 1-d array).
Maoying Wu SysBio
MATLAB variables
Variables are dynamically typed.
Variable types can be changed
Basic operations
sum, subtract, multiply, divide
power, sqrt, sin, cos, etc.
Maoying Wu SysBio
Scalars, Vectors and Arrays
1 × 1 arrays are also called scalars.
1 × N arrays are also called row vectors.
N × 1 arrays are also called column vectors
Row and column vectors are called vectors
Maoying Wu SysBio
Getting Started: Assignment
1 2 1
A= ,b = , Ax = b, x = A−1 b
2 1 2×2
2 2×1
a = [ 1 2; 2 1 ];
a
b = [1;2];
x = a\b
x = inv ( a ) * b
1×1 2×2
A. ∗ A0 = (A is symmetric)
2×2 1×1
a .* a
1×1+2×2 1×2+2×1
A∗A=
2×1+1×2 2×2+1×1
a*a
Maoying Wu SysBio
Exercise
1
Let π = be the initial probability for two states, and
0
0.8 0.1
T = be the transition probability matrix between
0.2 0.9
states 1 and 2.
pi = [1; 0];
t = [0.8 0.1; 0.2 0.9];
for i =1:20 , pi = t * pi , end
What do you notice? Explain the phenomenon.
Maoying Wu SysBio
Vector: initialization
x = []; % empty vector
x = [ x rand ]; % append a random element
Maoying Wu SysBio
Vector: Sorting
% generate 10 uniform random variables
x = rand (10 , 1) ;
% sorting
[y , ind ] = sort (x , ’ ascend ’) ;
% what the indices mean ?
all ( y == x ( ind ) )
% sort the indices
[~ , ind2 ] = sort ( ind , ’ ascend ’) ;
% what the ind2 mean ?
all ( x == y ( ind2 ) )
Maoying Wu SysBio
Vector: norm
n
xip )1/p
X
||x||p = (
i=1
% generate 10 uniform random variables
x = rand (10 , 1) ;
% l1 - norm
y = norm (x , 1) ;
% how to compute l1 - norm ?
sum ( abs ( x ) ) == y
% l2 - norm
z2 = norm (x , 2) ;
% how to compute the l2 - norm ?
z2 == sqrt ( sum ( x .^2) )
% l - infinity norm
zinf = norm (x , inf ) ;
max ( abs ( x ) ) == zinf
Maoying Wu SysBio
Vector: Histogram
x = rand (10 , 1) ;
x = x (:) ;
% histogram : the mid of bin and the count in each bin
[ count , mid ] = hist ( x ) ;
% how to get the bin , 10 bins
y = linspace ( min ( x ) , max ( x ) , 11)
all ( y (1:10) + ( y (2) -y (1) ) /2 == mid )
% count
count2 = [];
for i =1:10 , count2 ( i ) = sum (x >= y ( i ) & x <= y ( i +1) ) ; end
% are these two equal ?
all ( count == count2 )
Maoying Wu SysBio
Special double array
ones(n, m, p)
zeros(n, m, p, q)
rand(n, m)
randn(n, m)
cell(n, m)
Maoying Wu SysBio
Random array
s = rng ;
A = randn (5) ;
rng ( s )
B = randn (5) ;
A == B
Maoying Wu SysBio
The size command
If A is an array, then size(A) is a 1 × ndims(A) double array. And
the (1, k) entry is the length of the k th dimension of A.
Examples
A = rand (5 ,6 ,8) ;
B = size ( A ) ;
[ a1 , a2 , a3 , a4 ] = size ( A ) ;
[ a1 , a2 ] = size ( A ) ;
size (A , 2)
size (A , 6)
Maoying Wu SysBio
The class command
If A is an array, then class(A) is character string, whose value is
the class of A (e.g. double, char, cell, struct, uint32, etc.)
Examples
class ( rand (5 ,6) )
class ( ’ this is a string 1234.56 ’)
class (5==6)
class ( class ( rand (5 ,6 ,8) ) )
class ( cell (4 ,5) )
Maoying Wu SysBio
Struct array
Like cell arrays, structure arrays (class name is struct) allow
you to group different data types together.
Examples:
student . Name = ’ Fred Smith ’;
student . SID = 12345678;
student . Scores = [62 78 93 61];
size ( student )
class ( student )
fieldnames ( student )
isfield ( student , ’ Name ’)
isfield ( student , ’ Names ’)
student . Scores (3) = 99;
student . Scores ([1 end ])
c = struct ( ’ fld1 ’ , A , ’ fld2 ’ , B ) ;
Maoying Wu SysBio
File: opening, reading and writing
in_file = fopen ( ’ Name_of_File ’ , ’r ’) ; % read only
if ( in_file == -1)
error ( ’ oops , file can ’t be read ! ’) ;
end
[ number , count ] = fscanf ( file , ’%d ’ , 1) ;
while ( count == 1) % while we have read a number
fprintf ( ’ We just read % s \ n ’ , number ) ;
[ number , count ] = fscanf ( file , ’% d ’ , 1) ; % attempt to
read the next number
end
Maoying Wu SysBio
fprintf
fprintf ( ’% format \ n ’ , variable ) ;
%s: a string
%c: a single character
%d: a whole number
%f: a floating point number
\n: a newline
\t: a tab
\\: a slash
%%: a percent sign
Maoying Wu SysBio
Flow control
for loops
while loops
if/elseif/else conditionals
switch/case/otherwise
try/catch
Do NOT forget the end at the end.
Maoying Wu SysBio
while-loop and for-loop
Listing 1: while-loop
while < condition >
if < something - bad - happens >
break
else
% do something useful
end
% do more things
end
Listing 2: for-loop
for < condition >
if < something - bad - happens >
next
elseif
% do something useful
else
% do something useful
end
% do more things
end
Maoying Wu SysBio
Graphics in MATLAB
t = 0:.3:10;
y = sin ( t ) ;
plot (t , y ) ;
Maoying Wu SysBio
3D graphics in MATLAB
[x , y ] = meshgrid ( -2:.2:2 , -2:.2:2) ;
z = x .* exp ( - x .^2 - y .^2) ;
surf (x ,y , z )
Maoying Wu SysBio
Definition of Functions
function [N , M , Z ] = read_al ignment ( inputfile )
% reads alignment from inputfile , removes inserts and
converts into numbers
align_full = fastaread ( inputfile ) ;
M = length ( align_full ) ;
ind = align_full (1) . Sequence ~= ’. ’ & align_full (1) .
Sequence == upper ( align_full (1) . Sequence ) ;
N = sum ( ind ) ;
Z = zeros (M , N ) ;
for i =1: M
counter = 0;
for j =1: length ( ind )
if ( ind ( j ) )
counter = counter + 1;
Z (i , counter ) = letter2number ( align_full ( i ) .
Sequence ( j ) ) ;
end
end
end
Maoying Wu SysBio
Functions of the MATLAB Optimization
Linear and Quadratic minimization problems
linprog - Linear programming
quadprog - Quadratic programming
Nonlinear zero finding (equation solving)
fzero - Scalar nonlinear zero finding
fsolve - Nonlinear system of equations solve (function solve)
Linear least squares (of matrix problems)
lsqlin - Linear least squares with linear constraints.
lsqnonneg - Linear least squares with nonnegativity constraints.
Nonlinear minimization of functions:
fminbnd - Scalar bounded nonlinear function minimization.
fmincon - Multidimensional constrained nonlinear minimization.
fminsearch - Multidimensional unconstrained nonlinear minimization, by
Nelder-Mead direct search method.
fminunc - Multidimensional unconstrained nonlinear minimization.
fseminf - Multidimensional constrained minimization, semi-infinite
constraints.
Maoying Wu SysBio
Linear Programming
Linear programming problem
min f (x) = c T x
s.t.
Ax ≤ a
Bx = b
lb ≤ x ≤ ub;
Objective function: f (x) = c T x
Linear constraints: inequation (Ax ≤ a), equation (Bx = b),
box (lb ≤ x ≤ ub).
[x , fval , exitflag , output , lambda ] = linprog (f , A , a , B , b , lb
, ub , x0 , options ) ;
Maoying Wu SysBio
Algorithms under linprog
options = optimset ( ’ linprog ’) ;
a simplex algorithm (medium-scale)
options = optimset ( ’ LargeScale ’ , ’ off ’ , ’ Simplex ’ , ’ on ’
);
an active-set algorithm (medium-scale)
options = optimset ( ’ LargeScale ’ , ’ off ’ , ’ Simplex ’ , ’ off
’) ;
a primal-dual interior-point method (large-scale)
options = optimset ( ’ LargeScale ’ , ’ on ’) ;
Maoying Wu SysBio
Linear programming: Example 1
max 2x1 + 3x2
s.t.
x1 + 2x2 ≤8
2x1 + x2 ≤ 10
x2 ≤3
x1 , x2 ≥0
c = [ -2 , -3] ’;
A = [1 ,2;2 ,1;0 ,1];
a = [8 ,10 ,3] ’;
options = optimset ( ’ linprog ’) ;
options = optimset ( ’ LargeScale ’ , ’ off ’) ;
xsol = linprog (c , A , a , [] , [] , [0 ,0] ’ , [] , [] , options )
Maoying Wu SysBio
Linear programming: Exercise
1 1 1 1 1 1 10
(A|a) =
5 0 −3 0 1 0 15
1 2 3 0 0 0 5
0 1 2 3 0 0 7
max cT x (B|b) =
0 0 1 2 3 0 8
s.t. 0 0 0 1 2 3 8
Ax =a
3 0 0 0 −2 1 5
(D|d) =
Bx ≥b 0 4 0 −2 0 3 7
Dx ≤d
−2 7 1
lb ≤ x ≤ ub 0 2 −2
−1 2 3
(lb|ub|c) =
−1 3 −4
−5 4 5
1 10 −6
Maoying Wu SysBio
Linear programming: solution.m
A =[1 ,1 ,1 ,1 ,1 ,1;5 ,0 , -3 ,0 ,1 ,0]; a =[10 ,15] ’;
B1 =[1 ,2 ,3 ,0 ,0 ,0; 0 ,1 ,2 ,3 ,0 ,0;...
0 ,0 ,1 ,2 ,3 ,0;0 ,0 ,0 ,1 ,2 ,3]; b1 =[5 ,7 ,8 ,8]; b1 = b1 (:) ;
D =[3 ,0 ,0 ,0 , -2 ,1;0 ,4 ,0 , -2 ,0 ,3]; d =[5 ,7]; d = d (:) ;
lb =[ -2 ,0 , -1 , -1 , -5 ,1] ’; ub =[7 ,2 ,2 ,3 ,4 ,10] ’;
c =[1 , -2 ,3 , -4 ,5 , -6]; c = c (:) ;
B =[ - B1 ; D ]; b =[ - b1 ; d ];
[ xsol , fval , exitflag , output ]= linprog (c ,A ,a ,B ,b , lb , ub )
fprintf ( ’% s % s \ n ’ , ’ Algorithm Used : ’ , output . algorithm ) ;
disp ( ’ = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ’) ;
disp ( ’ Press Enter to continue ’) ; pause
options = optimset ( ’ linprog ’) ;
options = optimset ( options , ’ LargeScale ’ , ’ off ’ , ’ Simplex ’ , ’ on
’ , ’ Display ’ , ’ iter ’) ;
[ xsol , fval , exitflag ]= linprog (c ,A ,a ,B ,b , lb , ub ,[] , options ) ;
fprintf ( ’% s % s \ n ’ , ’ Algorithm Used : ’ , output . algorithm )
fprintf ( ’% s ’ , ’ Reason for termination : ’)
if ( exitflag )
fprintf ( ’% s \ n ’ , ’ Convergence . ’) ;
else
fprintf ( ’% s \ n ’ , ’ No convergence . ’) ;
end
Maoying Wu SysBio
User Interface (UI)
Maoying Wu SysBio