Zen and The Art of Matlab: Damian Gordon
Zen and The Art of Matlab: Damian Gordon
Damian Gordon
Hard work done by :
Daphne Gilbert
&
Susan Lazarus
Introduction to MatLab
• MatLab is an interactive, matrix-based
system for numeric computation and
visualisation
• MATrix LABoratory
• Used in image processing, image synthesis,
engineering simulation, etc.
References
• “Mastering MatLab” Duane Hanselman, Bruce
Littlefield
• “The MatLab Primer”
http://www.fi.uib.no/Fysisk/Teori/KURS/WRK/m
at/mat.html
• “The MatLab FAQ”
http://www.isr.umd.edu/~austin/ence202.d/matlab
-faq.html
Printed Circuit Board
Specific Bond Selected
Bond Shape Estimated
MATLAB Command Window
» help
HELP topics:
Creating Variables
>> varname = 12
varname =
12
OR
>> A = [
123
456
789]
Entering Matrices (2)
• To create an NxM zero-filled matrix
>> zeros(N,M)
• To create a NxN zero-filled matrix
>> zeros(N)
• To create an NxM one-filled matrix
>> ones(N,M)
• To create a NxN one-filled matrix
>> ones(N)
Entering Matrices (3)
• To create an NxM randomly-filled matrix (which
is uniformly distributed)
>> rand(N,M)
OR
a b c
» whos
Name Size Bytes Class
»A+B
ans =
4 4 4
6 6 6
8 8 8
Matrix Subtraction
» A = [ 1 1 1 ; 2 2 2 ; 3 3 3]
» B = [3 3 3 ; 4 4 4 ; 5 5 5 ]
»B-A
ans =
2 2 2
2 2 2
2 2 2
Matrix Multiplication
» A = [ 1 1 1 ; 2 2 2 ; 3 3 3]
» B = [3 3 3 ; 4 4 4 ; 5 5 5 ]
»A*B
ans =
12 12 12
24 24 24
36 36 36
Matrix - Power
»A^2
ans =
6 6 6
12 12 12
18 18 18
»A^3
ans =
36 36 36
72 72 72
108 108 108
Matrix Transpose
A=
1 1 1
2 2 2
3 3 3
» A'
ans =
1 2 3
1 2 3
1 2 3
Matrix Division
Left Division \ Right Division /
x = A\B (is A*x=B) x=A/B (is x*A=B)
=> A * C = B => C * A = B
Matrix Operations
+ Addition • Add matrices
- Subtraction • Subtract matrices
* Multiplication Matrix Multiplication
^ Power • Raise to the power
‘ Conjugate Transpose • Get transpose
\ Left Division • x = A\B (is A*x=B)
/ Right Division • x=A/B (is x*A=B)
Philosophiae Naturalis
Principia Matlabematica
Damian Gordon
Getting to Matlab
Magic Matrix
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Upper Triangle Matrix
» a = ones(5) » triu(a)
a= ans =
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 0 1 1 1 1
1 1 1 1 1 0 0 1 1 1
1 1 1 1 1 0 0 0 1 1
1 1 1 1 1 0 0 0 0 1
Lower Triangle Matrix
» a = ones(5) » tril(a)
a= ans =
1 1 1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 0 0 0
1 1 1 1 1 1 1 1 0 0
1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1 1 1
Hilbert Matrix
» hilb(4)
ans =
ans =
K = find(abs(x) > 1)
K=
1267
The ‘FIND’ Command (2)
A = [ 1 2 3 ; 4 5 6 ; 7 8 9]
3 1
3 2
2 3
3 3
Special Variables
• ans - default name for results
• pi - pi
• eps - “help eps”
• flops - count floating point ops
• inf - Infinity, e.g. 1/0
• NaN - Not a number, e.g. 0/0
• i,j - root minus one
• why - why not ?
LOGO Command
The ‘PLOT’ Command (1)
>> X = linspace(0, 2*pi, 30);
>> Y = sin(X);
>> plot(X,Y)
>> Z = cos(X);
>> plot(X,Y,X,Z);
The ‘PLOT’ Command (2)
>> W = [Y ; Z]
>> plot (X,W)
Rotate by 90 degrees
>> plot(W,X)
The Meditations of
Matlab Aurelius
The ‘PLOT’ Command (1)
>> X = linspace(0, 2*pi, 30);
>> Y = sin(X);
>> plot(X,Y)
>> Z = cos(X);
>> plot(X,Y,X,Z);
The ‘PLOT’ Command (2)
>> W = [Y ; Z]
>> plot (X,W)
Rotate by 90 degrees
>> plot(W,X)
PLOT Options
>> plot(X,Y,’g:’)
>> plot(X,Y,’r-’)
>> plot(X,Y,’ko’)
>> plot(X,Y,’g:’,X,Z,’r-’,X,Y,’wo’,X,Z,’c+’);
PLOT Options
>> grid on
>> grid off
>> xlabel(‘this is the x axis’);
>> ylabel(‘this is the y axis’);
>> title(‘Title of Graph’);
>> text(2.5, 0.7, ’sin(x)’);
>> legend(‘sin(x)’, ‘cos(x)’)
SUBPLOT Command
• Subplot(m,n,p)
– creates a m-by-n matrix in and plots in the pth
plane.
subplot(2,2,1)
plot(X,Y)
subplot(2,2,2)
plot(X,Z)
subplot(2,2,3)
plot( X,Y,X,Z)
subplot(2,2,4)
plot(W,X)
Specialised matrices
• compan • Companion matrix
• gallery • Higham test matrices
• hadamard • Hadamard matrix
• hankel • Hankel matrix
• pascal • Pascal matrix.
• rosser • Classic symmetric
eigenvalue test problem
• vander
• Vandermonde matrix
• wilkinson
• Wilkinson's eigenvalue
test matrix
Polynomials
Polynomials are represented as
row vectors with its coefficients in
descending order, e.g.
X4 - 12X3 + 0X2 +25X + 116
p = [1 -12 0 25 116]
Polynomials
The roots of a polynomial are found as
follows
r = roots(p)
polyans = poly(r)
mypolyans = real(polyans)
Polynomial Addition/Sub
• a = [1 2 3 4]
• b = [1 4 9 16]
• c=a+b
• d=b-a
Polynomial Addition/Sub
• What if two polynomials of different
order ?
X3 + 2X2 +3X + 4
X6 + 6X5 + 20X4 - 52X3 + 81X2 +96X + 84
• a = [1 2 3 4]
• e = [1 6 20 52 81 96 84]
• f = e + [0 0 0 a] or f = e + [zeros(1,3) a]
Polynomial Multiplication
• a = [1 2 3 4]
• b = [1 4 9 16]
Perform the convolution of two arrays !
• g = conv(a,b)
g=
1 6 20 50 75 84 64
Polynomial Division
• a = [1 2 3 4]
• g = [1 6 20 50 75 84 64]
Perform the deconvolution of two arrays !
[q,r] = deconv(g, a)
q= {quotient}
1 4 9 16
r= {remainder}
00000000
Polynomial Differentiation
• f = [1 6 20 48 69 72 44]
• h = polyder(f)
h=
6 30 80 144 138 72
Polynomial Evaluation
x = linspace(-1,3)
p = [1 4 -7 -10]
v = polyval(p,x)
• ‘1/(2*x^n)’
• cos(x^2) - sin(x^2)
• M = sym(‘[a , b ; c , d]’)
• f = int(‘x^3 / sqrt(1 - x)’, ‘a’, ‘b’)
Symbolic Expressions
diff(‘cos(x)’)
ans =
-sin(x)
det(M)
ans =
a*d - b * c
Symbolic Functions
• numden(m) - num & denom of polynomial
• symadd(f,g) - add symbolic polynomials
• symsub(f,g) - sub symbolic polynomials
• symmul(f,g) - mult symbolic polynomials
• symdiv(f,g) - div symbolic polynomials
• sympow(f,’3*x’) - raise f^3
Advanced Operations
• f = ‘1/(1+x^2)’
• g = ‘sin(x)’
compose(f,g) % f(g(x))
ans=
1/(1+sin(x)^2)
Advanced Operations
• finverse(x^2)
ans =
x^(1/2)
• type mymatrix
IF Condition
if condition If x = 2
{commands} output = ‘x is even’
end end
WHILE Loop
X = 10;
while condition count = 0;
{commands} while x > 2
end x = x / 2;
count = count +
1;
end
FOR Loop
for n = 1:10
x(n) = sin(n);
end
for x=array
{commands} A = zeros(5,5); %
end prealloc
for n = 1:5
for m = 5:-1:1
A(n,m) = n^2 + m^2;
end
disp(n)
end
Creating a function
function a = gcd(a,b)
% GCD Greatest common divisor
% gcd(a,b) is the greatest common divisor of
% the integers a and b, not both zero.
a = round(abs(a)); b = round(abs(b));
if a == 0 & b == 0
error('The gcd is not defined when both numbers are zero')
else
while b ~= 0
r = rem(a,b);
a = b; b = r;
end
end
Quick Exercise (!)
• Consider Polynomial Addition again :
how would you write a program that takes in two
polynomials and irrespective of their sizes it adds the
polynomials together ? Given that the function length(A)
returns the length of a vector.
Answers on a postcard to : [email protected]
length(b)) b];
Recursion
function b = bart(a)
%BART The Bart Simpson program writes on the blackboard
% program, Bart writes the message a few times
% and then goes home to see the Simpsons
if a == 1
disp('I will not....');
else
disp('I will not skateboard in the halls');
bart(a - 1);
end
Curve Fitting
• What is the best fit ?
– In this case least squares curve fit
• What curve should be used ?
– It depends...
POLYFIT : Curve Fitting
• polyfit(x,y,n) - fit a polynomial
z = polyval(p,xi)
plot(x,y,'o',x,y,xi,z,':');
Interpolation - 1D
• t = interp1(x,y,.75)
t=
9.5200
also
• interp1(x,y,.75,’spline’)
• interp1(x,y,.75,’cubic’)
Interpolation - 2D
• interp2(x,y,Z,xi,yi,TYPE)
TYPE =
• ‘Tensors’
• ‘Tensors.html’
3D Graphics
T = 0:pi/50:10*pi;
plot3(sin(t), cos(t), t);
3D Graphics
title('Helix'), xlabel('sin(t)'),
ylabel('cos(t)'), zlabel('t')
grid
3D Graphics
• Rotate view by elevation and azimuth
view(az, el);
view(-37.5, 60);