Lecture 17

Introduction to Matlab
Introduction to Matlab
1. Vectors, matrices, and arithmetic
2. Plotting
3. Flow Constructs
4. Other Useful Things
1
Why use Matlab?
• Advantages:
Handles vector and matrices very nicely
Quick plotting and analysis
EXTENSIVE documentation (type ‘help’)
Lots of nice functions: FFT, fuzzy logic, neural
nets, numerical integration, OpenGL (!?)
• Drawbacks:
Slow compared to C or Java
Vectors and Matrices
• Can be run from command line or from *.m file
scalar:
x=3
vector:
x = [1 0 0]
2D matrix: x = [1 0 0; 0 1 0; 0 0 1]
arbitrarily higher dimensions possible
• Can also use matrices / vectors as elements:
x = [1 2 3]
y = [ x 4 5 6]
2
Some Standard matrices
•
•
•
•
•
ones(3,3)
3x3 of all ones
zeros(3,3)
3x3 of all zeros
eye(3,3)
3x3 identity
rand(3)
3x3 random elements
linspace(1,10,100)
linear spacing from 1 to 10, with 100
spacings (also logspace)
• x = 1:10
linear spacing from 1 to 10, counting by 1
Accessing elements
•
•
•
•
•
•
MATLAB IS NOT ZERO INDEXED!
x
retrieves entire matrix x
x(1,2)
retrieves element at row 1, col 2
x(1, 5:10)
retrieves row 1, columns 5 to 10
x(1,:)
retrieves row 1, all columns
Useful functions:
length(x) length of vector x (cols)
size(x)
rows, cols of x
3
Matrix Operations
• For matrix operations
– Dimensions must agree
• Scalar operations
– Same as usual
• Scalar / matrix mixed
– Scalar + matrix = [scalar + matrix(x, y)]
– Scalar * matrix = [scalar * matrix(x, y)]
More Matrix Operations
• The ‘.’ operator
– “element by element” access
• Example:
– x = [1 2 3]; y = [4; 5; 6];
– x * y = 32
– x .* y = [4 10 18]
• For some functions :
– x ^ 2 ERROR!
– x . ^2 fine
4
More Matrix Operations
•
•
•
•
•
•
•
•
x=1:12
reshape(x, 3,4)
a=2*ones(3,4)
X.*a
b=[1:3;1:3;1:3;1:3]
X.*b
y=reshape(x, 4,3)
y.^b
Plotting
• 2D graphing
plot(x,y)
• Example:
x = linspace(-10,10,100)
y = x .^2
plot(x,y)
• Also:
z = x .^3
plot(x,z)
5
Plotting Example
basis = [
[1 0];
[0 0];
[0 1];
]'
;
square = [
[ 1 1]
[-1 1];
[-1 -1];
[ 1 -1];
[ 1 1];
axis equal;
plot( sqrt(3), sqrt(3), '
w.');
plot( -sqrt(3), -sqrt(3), '
w.');
plot( basis(1,:), basis(2,:), '
k'
);
plot( square(1,:), square(2,:), '
b'
);pause
obj = S*square;
plot( obj(1,:), obj(2,:), '
r'
);pause
]'
;
basis = [
Plotting Example
[1 0];
[0 0];
[0 1];
[1 0];
]'
;
square = [
[ 1 1];
[-1 1];
[-1 -1];
[ 1 -1];
[ 1 1];
6
More Plotting
• Graphics Window
– To open a new graph, type ‘figure’
• Multiple data sets:
– Type ‘hold on’ to add new plot to current graph
– Type ‘hold off’ to resume default mode
• Make your graph beautiful:
– title(‘apples over oranges’)
– xtitle(‘apples’)
– ytitle(‘oranges’)
3D Plotting
• 3D plots – plot an outer product
x = 1:10
y = 1:10
z = x’ * y
mesh(x,y,z)
Single quote ‘ means transpose
7
Flow Control
• IF block
if (<condition>)
<body>
elseif
<body>
end
• WHILE block
while (<condition>)
<body>
end
Conditions same as C, ( ==, >=, <=) except != is ~=
More Flow Control
• FOR block
for i = 1:10
<body>
end
• SWITCH statement
switch <expression>
case <condition>,
<statement>
otherwise <condition>,
<statement>
end
8
Other Language Features
• Matlab language is pretty sophisticated
– Functions
Stored in a *.m file of the same name:
function <return variable> = <function name>(<args>)
<function body>
– Structs
• point.x = 2; point.y = 3;
point.z = 4;
Useful Commands
• Single quote is transpose
• %
same as // comment in C, Java
No /* block comments */
• ;
suppresses printing
• More:
max(x)
mean(x)
abs(x)
cross(x,y)
min(x)
median(x)
dot(x,y)
flops (flops in this session)
9
Useful Constants
•
•
•
•
•
•
Inf
NaN
eps
ans
pi
i and j
infinity
Not a number (div by zero)
machine epsilon (precision)
most recent unassigned answer
3.14159….
Matlab supports imaginary
numbers!
Programming
• Wrong:
for x = 1:10
for y = 1:10
foo(x,y) = 2 * bar(x,y)
end
end
• Right:
foo = 2 * bar;
• Matlab is optimized for vectorization
10
Symbolic Maths
• Symbolic mathematics can be done using Matalb:
a = sqrt(sym(2))
a=
2^(1/2)
th=sym('
th'
);
rt=sym([cos(th) sin(th) 0;-sin(th) cos(th) 0;0 0 1]);
rt =
[ cos(th), sin(th),
0]
[ -sin(th), cos(th),
0]
[
0,
0,
1]
Good luck
11