Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 45

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

The MATLAB Family


MATLAB
MATLAB Extensions/ MATLAB Compiler, C/C++ Math Library
Toolboxes
Simulink
SIMULINK Extensions/ Accelerator, Real-Time Workshop
Blocksets
...
4
Working with Matrices
Entering Matrices
A = [ 0.6 3 2; 5 10 2; 9 -6 7]

Separate the elements of a row with blanks or commas


Use a semicolon to indicate the end of each row
Surround the entire list of elements with [ , ]

Subscripts
A(1,2) + A(2,3)
A(3)

A(i, j) = the element in row i and column j

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

A(1:2, :) = the submatrix(23) of A


A(4, 1) = the dimension of A increases automatically

1:10, 1:3:14
6
Working with Matrices
sum, transpose, diag
sum(A)
A'
diag(A)

sum(A) = the sum over each column


A' = AT
diag(A) = picks off the diagonal of 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)

zeros = generate a zero matrix


ones = generate an ones matrix
eye = generate an identity matrix

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);

lu(A) : LU decomposition of matrix A


svd(A) : sigular value decomposition of matrix A
qr(A) : QR decomposition of matrix A
null(A) : orthonormal basis for the null space of A
rref(A) : row-reduced echelon form
11
More about Matrices
Arrays(element-wise operations)
A .* B
A .^ 2
A^2
X = [2 1+j; 4j 2]
X'
X.'

.* = 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)

= recall previous command


= recall next command
= clear command
15
Command Window
Variables
pi_value = 3.141592
string1 = 'Hello, Matlab!'
String1
pi
eps

Any type declarations or dimension statements is not necessary


Variable name = a letter + letters/digits/underscores
The first 31 characters of a variable name is used
Variable names are case sensitive
pi = 3.1415926535897....
eps = floating point relative accuracy.
realmin, realmax, inf, nan
16
Command Window
Exercise #3
a = (3==2);
ans
b=a
ans

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

workspace = the area of memory used by the MATLAB


who = lists the current variables in the workspace
clear = clear the workspace
save = save the workspace variables to a file.
load = load all variables from a specified file.

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)

plot(x1, y1, x2, y2, ...)

plot(t, y, 'c--', t, y2, 'r.')

plot(x1, y1, 'color_style_marker', x2, y2, 'color_style_marker, ...)


color_style_marker = a 1/2/3 character string.
color = c, m, y, r, g, b, w, k
style = -, --, :, -., none
marker = +, o, *, x
25
Basic 2-D Graphics
Subplots
clf
y4 = cos(t);
subplot(2, 2, 1); plot(t, y)
subplot(2, 2, 2); plot(t, y2)
subplot(2, 2, 3); plot(t, y3)
subplot(2, 2, 4); plot(t, y4)

clf = clear the current figure window


subplot = display multiple plots in the same window

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)')

grid on = draw the grid lines


axis([xmin xmax ymin ymax]) = set scaling for the axes
xlabel/ylabel = adds text beside the X-axis/Y-axis

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

Process to write M-files


Create an M-file using a text editor
Call the M-file from the command window, or from within another M-file

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

Call the M-file


plotsine
whos
Scripts automate a series of commands
30
Flow Control
Four flow control statements
if
switch
while
for

break, continue, return

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

disp = display the given string/array


end cannot be omitted
if ~ end
if ~ else ~ end
32
Flow Control
switch
n = 3;
switch n
case 1
disp('1')
case {2, 3, 4}
disp('2 or 3 or 4')
otherwise
disp('something else')
end

case' + a possible value for the expression, all on a single line


otherwise' can be omitted

33
Flow Control
for
for i = 1:5
for j = 1:3
A(m, n) = 1/(i+j);
end
end

for' loop executes statements a predetermined number of times


for index = start:increment:end
statements
end
the default increment is 1

34
Flow Control
while
sum = 0;
n = -2;
while n <= 5
sum = sum + n;
n = n + 1;
end
sum

The while' loop executes statements repeatedly as long as the


controlling expression is true(1)
while expression
statements
end
35
M-File Functions
Simple function example
function mv = avg(x)
% Mean of a vector, NOT a matrix
[m, n] = size(x);
if ~(m == 1) & ~(n == 1)
error('Input must be a vector')
end
mv = sum(x) / length(x);
save the above as avg.m

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 = ...

Function definition line


H1 line
Function help text
Function body
37
M-File Functions
Function name
has the same constraints as variable name
ONE function in ONE file cf) subfunction
file name > function name
The name of the M-file and of the function SHOULD be the same

Function name resolution


Check to see if the name is a variable
Check to see if the name is a subfunction
Check to see if the name is a function on the current directory
Check to see if the name is a function on the MATLAB search path

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

eval : execute the contents of bracket in command window

for n = 0:pi/10:pi
m=feval('sin',n);
disp([n m])
end

feval : evaluate function by function name and argument(s) in bracket

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

You might also like