Professional Documents
Culture Documents
Basic Usage of Matlab
Basic Usage of Matlab
Introduction to MATLAB
Contents
What is MATLAB?
Working with Matrices
Expressions
Flow Control
MATLAB Environment
More about Matrices
M-File Programming
Functions
Basic 2-D Graphics
Basic 3-D Graphics
Simple GUI
2
Introduction to MATLAB
What is MATLAB?
A language for technical computing
An interactive system whose basic data element is a matrix
MATLAB stands for MATrix LABoratory
Typical Uses
Math and computation
Algorithm development
Modeling, simulation, and prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
Application development including GUI
3
Introduction to MATLAB
Features
Every MATLAB data object is a matrix
Functions may return multiple values
MATLAB functions are vectorized
MATLAB matrices store data in column-major
Subscripts
A(1,2) + A(2,3)
A(3)
5
Working with Matrices
Colon operator
A(3, :)
A(:, 2)
A(i, :) = the i-th row of A
A(:, j) = the j-th column of A
A(1:2, :)
A(1:2, 1:2)
A(4, 1) = 1
1:10, 1:3:14
6
Working with Matrices
sum, transpose, diag
sum(A)
A'
diag(A)
7
Working with Matrices
Exercise #1
X = [ 1 2 3 4 5 6 7 8 9 10 11 12]
Y = X(:) or Y=X'
Z = reshape(X,3,4)
W = reshape(Y,4,3)
Problem #1
Find difference between diag([1 2]) and diag([1 0; 0 2])
8
More about Matrices
Useful Matrices
zeros(2, 4)
ones(3)
eye(2)
Concatenation
A = [1 2; 3 4]
B = [-1 -2; -3 -4]
C = [A B; B A]
9
More about Matrices
Deleting Rows and Columns
C(:, 2) = [ ]
C(3, :) = [ ]
Matrix operation
dA = det(A)
iA = inv(A)
iA*A
ce = poly(A)
roots(ce)
det(A) = determinant of A
inv(A) = inverse of A
10
More about Matrices
Some Linear Algebra
A = [1 2 3; 4 5 6; 7 8 9];
r = rank(A); s=cond(A);
B = lu(A);
C = svd(A);
D = qr(A);
E = null(A)
F = rref(A);
.* = element-by-element multiplication
.^ = element-by-element power
.' = unconjugated transpose
./ .\
12
More about Matrices
Exercise #2
A = [ 1+i 2+j 3; 4-4j 5i 6]
size(A)
length(A) % =max(size(A))
Problem #2
Write a program which sorts eigenvalue of matrix A by its magnitude.
Assume that no eigenvalues are same each other.
Watch out complex number. (hint: eig, sort)
13
Command Window
format
Format short
A=[pi 1.4e4 -4/3]
Format long
A
format = switch between different output display formats
ans
ans
ans = the variable which stores the results of most recent answer
14
Command Window
help
help format
help help
help = gives help on the specified topic.
A(1,2)
Problem #3
What is difference of cd and pwd
17
Expressions and Math Functions
Numbers
0.0001
1.602e-5
3i
0.41E2j
All numbers are stored internally using the long format
i = 2 3i 3*i 1.602e-5 = 1.60210-5
i=2
3i
3*i
i, j = imaginary unit
Don't use i or j as a variable except for-loop index!!!
18
Expressions and Math Functions
Operators
a=4
b = 1 + 2j
c = a^2
d = a^-0.5
e = b'
^ = power
' = complex conjugate transpose
A = [ 3 2; 2 1]
B = [ 2 1; 1 0]
C = A*B
A^2 - A*A
19
Expressions and Math Functions
Math Functions
sin(a)
abs(b)
sqrt(c)
exp(1)
log(10)
a = sqrt(-1)
b = sqrt(i)
sqrt =
exp(x) = ex
log = natural logarithm
20
Expressions and Math Functions
Exercise #4
A = [0 30; 45 60]*pi/180
B = sin(A)
C = A^-1 - inv(A)
Problem #4
1) Try exp(A) and expm(A), where A=eye(2), and tell difference.
2) Write one-line code which shows the angle of two vectors.
veca=[2,1];
vecb=[1,2];
angle= ....
21
MATLAB Environment
Workspace
save my.dat
clear
clc
who
load my.dat -mat
who
22
MATLAB Environment
save
save mywork2 a b c
save am.dat -ascii A
save mywork2 a b c = save a, b, c variables in the mywork2.mat
save am.dat -acii A = save A to am.dat in 8-digit text format
When save workspace variables in text format,
you SHOULD save only one variable to a file.
Disk file
dir = dir/ls
type = type/cat
delete = del/rm
diary
23
Basic 2-D Graphics
Creating a Plot
t = 0:pi/100:2*pi;
y = sin(t);
plot(t, y)
plot(x, y) = produces a 2D graph of y vs. x
figure
y2 = sin(t - 0.25);
plot(t, y2)
hold on
plot(t, y+y2)
figure = open a new figure window
hold on/off = allows you to add plots to an existing graph ans = the
variable which stores the results of most recent answer
24
Basic 2-D Graphics
plot Command
y3 = sin(t - 0.5);
plot(t, y, t, y2, t, y3)
26
Basic 2-D Graphics
Axes
clf
t = -pi:pi/100:pi;
y = sin(t);
plot(t, y)
grid on
axis([-pi pi -1 1])
xlabel('\pi \leq \itt \leq \pi')
ylabel('sin(t)')
27
Basic 2-D Graphics
Exercise #5
figure;
plot((0:0.5:20),sin(0:0.5:20),'ro');
Hold on;
plot((0:0.5:20),sin(0:0.5:20),'b:')
figure(3); t=(0:0.5:20)';
plot(t, sin(t),'g.',t,cos(t),'m+');
title('Graph of sin(t)')
Problem #5
Practice the command 'legend', 'gtext', 'line' and 'text'
28
M-File
M-File
Files that contain MABLAB language code
File name = filename.m
File names are NOT case sensitive
Two types = Script, Function
29
M-File Scripts
Create an M-file using a text editor
clear
t = -pi:pi/100:pi;
y = sin(t);
plot(t, y)
xlabel('t [rad]')
ylabel('sin(t)')
save the above as plotsine.m
Relational operators
< <= > >= == ~=
true = 1 false = 0
Logical operators
& | ~
31
Flow Control
if, elseif, else, end
n = 3;
if n > 0
disp('Positive')
elseif n < 0
disp('Negative')
else
disp('Zero')
end
33
Flow Control
for
for i = 1:5
for j = 1:3
A(m, n) = 1/(i+j);
end
end
34
Flow Control
while
sum = 0;
n = -2;
while n <= 5
sum = sum + n;
n = n + 1;
end
sum
A = [1 2 3 4]; ma = avg(A)
B = [1 2; 3 4]; mb = avg(B)
36
M-File Functions
The anatomy of a function
function [r1, r2] = fname(x)
% H1 line
% Function help text
...
Function body
...
r1 = ...
r2 = ...
38
M-File Functions
local and global variables
function value=tg(x, y)
global Z
x1 = x^2; y1 = y^2; Z1 = Z^2
value=x1+y1+z1; return
save as tg.m
Declare the variable as golbal in every function that requires access to it
Issue the global command at the top of the M-file (Recommended!!)
global Z
x = 3; y = 4; Z= 5;
tg(x, y)
x, y, Z
save as test.m and run test!
39
M-File Functions
eval and feval
for n = 1:12
eval(['M' num2str(n) ' = magic(n)'])
end
for n = 0:pi/10:pi
m=feval('sin',n);
disp([n m])
end
40
M-File Functions
Project #1
Write function val = equ(x); val=x+exp(x)-5; function gra = der(x);
gra=1+exp(x); % der : derivative function % xo : initial guess your own
program (m-flie function) which returns a root of nonlinear boolean equation.
The Equation is given by 'equation.m' and its gradient is given by
'derivative.m'. (Newton-algorithm)
function sol = findroot(equ, der, xo);
% equ : equation function
% der : derivative function
% xo : initial guess
Test your code by
function val = equ(x); val=x+exp(x)-5;
function gra = der(x); gra=1+exp(x);
% der : derivative function
% xo : initial guess
41
Basic 3-D Graphics
plot3(x,y,z)
plots x,y,z in 3-dimentional space
t=(0:pi/10:8*pi);
x=exp(-t/20).*cos(t);
y=exp(-t/20).*sin(t);
z=t;
figure(1); plot3(x,y,z);
xlabel('x'); ylabel('y'); zlabel('z');
view(Az,El)
Specifies the viewing point in 3-dimentional plot
view(20,70); view(2); view(3);
42
Basic 3-D Graphics
meshgrid(x,y)
generates domain for plotting
x=(-5:0.2:5);
y=(-5:0.2:5);
[X,Y] = meshgrid(x,y);
Z= X .* exp(-X.^2 - Y.^2);
size(X); size(Y); size(Z);
mesh(Z)
plots colored meshed 3-D graph
mesh(Z); mesh(X,Y,Z);
43
Basic 3-D Graphics
surf
plots 3-d surface graphs
surf(X,Y,Z)
contour
plots 3-d surface graphs
[cs,h]=contour(Z)
clabel(cs,h);
colorbar;
44
Basic 3-D Graphics
Exercise #6
clear all; clear all;
[x, y, z] = sphere(25);
surf(x-3,y-2,z);
Hold on;
surf(x*2,y*2 z*2);
grid on; cloorbar
Problem #6
plot cube box whose line magnitude is 3.
(cf: line, fill3)
45