You are on page 1of 68

MATLAB

Application Software
Tool
Satish Chavan
Assistant Professor
Department of Electronics & Telecommunication
Don Bosco Institute of Technology, Kurla
References
 Rudra Pratap, “Getting Started with MATLAB: A
Quick Introduction for Scientists and Engineers, ”
Oxford University Press, 2002.
 Brain R. Hunt, Ronald L. Lipsman, Jonathan M.
Rosenberg, “A Guide to MATLAB for Beginners
and Experienced Users,” Cambridge University Press,
2001
 Delores M. Etter, David C. Kuncicky, Doug Hull,
“Introduction to Matlab7,” Third Edition,
Pearson Education, 2006
 www.mathworks.com

July 28, 2010 Satish Chavan, DBIT 2


Agenda
 What is Matlab?
 Key Features
 Be familiar with Matlab
Environment
 A game of Matrices
 Matlab Basics
 Use of Matlab in Signal Processing
July 28, 2010 Satish Chavan, DBIT 3
Matlab
 It is a software package for high
performance numerical computation
& visualization.
 It was originally designed for solving linear
algebra type problems using matrices.
 It’s name is derived from MATrix
LABoratory.

July 28, 2010 Satish Chavan, DBIT 4


Matlab
 Originally Written in FORTRAN
 By Cleve Moler

 Interactive Access to
LINPACK/EISPACK
 Trusted numeric and matrix
computation techniques

July 28, 2010 Satish Chavan, DBIT 5


Matlab
 Early Public Distribution
 Limited scripting, line-printer graphics
 Originally on mainframes, DOS and MAC
versions followed
 Current Commercial Form / The
MathWorks Inc.
 Core is written in C, Extremely extensible
 Runs on many platforms, optimized interface and
computations
 Professional and Student Editions
 Extensions include “SIMULINK” and various
“TOOLBOXES”

July 28, 2010 Satish Chavan, DBIT 6


Features & Capabilities
MATLAB

Matlab Programming Language

Use written Function


Built in Functions

Graphic Computatio External


Extra Functions

Extra Functions
s
• 2D graphics •Linear Algebra
ns Interface (Mex
•Data Analysis
• 3-D graphics
•Signal Processing •Files)
Interface with C
• Color & Lighting and Fortran Programs
• Animation •Polynomials & Interpolations
•Quadrature
•Solutions of ODEs

Toolboxes (Collection of Specialized


• Signal Processing • Neural Network • Robust Control
Functions)
• Statistics • Communications • Optimization
• Control Systems • Image Processing
July 28, 2010 Satish
Such many more Chavan,
toolboxes DBIT • Financial
are available 7
The MATLAB ® system
 Development Environment
 The MATLAB Mathematical
Function Library
 The MATLAB Language
 Graphics
 The MATLAB Application
Program Interface (API).   

July 28, 2010 Satish Chavan, DBIT 8


Matlab Desktop
 Command Window
 Command History
 Start Button and Launch

 Help Browser
 Current Directory Browse

 Workspace Browser
 Array Editor
 Editor/Debugger
 Profiler  
 Figure Window
July 28, 2010 Satish Chavan, DBIT 9
Command Window

July 28, 2010 Satish Chavan, DBIT 10


Command History

July 28, 2010 Satish Chavan, DBIT 11


Start Button

July 28, 2010 Satish Chavan, DBIT 12


Launch Pad

July 28, 2010 Satish Chavan, DBIT 13


Help Browser

July 28, 2010 Satish Chavan, DBIT 14


Current Directory
Browser

July 28, 2010 Satish Chavan, DBIT 15


Workspace Browser

July 28, 2010 Satish Chavan, DBIT 16


Array Editor

July 28, 2010 Satish Chavan, DBIT 17


Editor/Debugger

July 28, 2010 Satish Chavan, DBIT 18


Profiler

July 28, 2010 Satish Chavan, DBIT 19


Figure Window Title

Y label

X label 2-D Plot Image

July 28, 2010 Satish Chavan, DBIT 20


Getting Help
 General information
 help -- M-file help, displayed at the command line.

 helpwin -- M-file help, displayed in the help

browser.
 lookfor -- Search all M-files for keyword.

 demo -- Run demonstrations.

 Ver -- MATLAB, SIMULINK, and toolbox version

information.
 version -- MATLAB version information.

 Using the Help Browser (.html, .pdf)


 View getstart.pdf, graphg.pdf, using_ml.pdf

July 28, 2010 Satish Chavan, DBIT 21


MATLAB Variable Names
 Variable names ARE case sensitive

 Variable names can contain up to 63


characters (as of MATLAB 6.5 and newer)

 Variable names must start with a letter


followed by letters, digits, and
underscores.

July 28, 2010 Satish Chavan, DBIT 22


MATLAB Special Variables
ans Default variable name for results
pi Value of π
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i and j i = j = square root of -1
realmin The smallest usable positive real
number
realmax The largest usable positive real
number
July 28, 2010 Satish Chavan, DBIT 23
MATLAB Math & Assignment Operators

Power ^ or .^ a^b or a.^b


Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
or \ or .\ b\a or b.\a
NOTE: 56/8 = 8\56

Addition + a + b
Subtraction - a - b
Assignment = a = b (assign b to a)

July 28, 2010 Satish Chavan, DBIT 24


Other MATLAB symbols

>> prompt
... continue statement on next line
, separate statements and data
% start comment which ends at end of line
; (1) suppress output
(2) used as a row separator in a matrix
: specify range

July 28, 2010 Satish Chavan, DBIT 25


Relational and Logical Operators
Operator Description

& Returns 1 for every element location that is true


(nonzero) in both arrays, and 0 for all other elements.
| Returns 1 for every element location that is true
(nonzero) in either one or the other, or both, arrays and 0
for all other elements.
~ Complements each element of input array, A.
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
July 28, 2010 Satish Chavan, DBIT 26
Data Types

July 28, 2010 Satish Chavan, DBIT 27


MATLAB Matrices
 MATLAB treats all variables as matrices. For
our purposes a matrix can be thought of as an
array, in fact, that is how it is stored.

 Vectors are special forms of matrices and


contain only one row OR one column.

 Scalars are matrices with only one row AND


one column

July 28, 2010 Satish Chavan, DBIT 28


MATLAB Matrices
 A matrix with only one row AND one
column is a scalar. A scalar can be
created in MATLAB as follows:

» a=23
a=
23

July 28, 2010 Satish Chavan, DBIT 29


MATLAB Matrices
 A matrix with only one row is called a row
vector. A row vector can be created in
MATLAB as follows (note the commas):

» r = [12 , 14 , 63]

r=
12 14 63

July 28, 2010 Satish Chavan, DBIT 30


MATLAB Matrices
 A matrix with only one column is called
a column vector. A column vector can
be created in MATLAB as follows (note
the semicolons):
» c= [13 ; 45 ; -2]
c=
13
45
-2

July 28, 2010 Satish Chavan, DBIT 31


MATLAB Matrices
 A matrix can be created in MATLAB as
follows (note the commas AND
semicolons):

» x = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]
x=
1 2 3
4 5 6
7 8 9
July 28, 2010 Satish Chavan, DBIT 32
Extracting a Sub-Matrix
 A portion of a matrix can be extracted and stored
in a smaller matrix by specifying the names of
both matrices and the rows and columns to
extract. The syntax is:

sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;

where r1 and r2 specify the beginning and ending


rows and c1 and c2 specify the beginning and
ending columns to be extracted to make the new
matrix.

July 28, 2010 Satish Chavan, DBIT 33


MATLAB Matrices
 A column vector can  Here we extract
be extracted from a column 2 of the
matrix. As an matrix and make a
example we create a column vector:
matrix below:
» x=[1,2,3;4,5,6;7,8,9] » y=x( : , 2)
x= y =
1 2 3 2
4 5 6 5
7 8 9 8

July 28, 2010 Satish Chavan, DBIT 34


MATLAB Matrices
 A row vector can be  Here we extract row 2
extracted from a of the matrix and
matrix. As an make a row vector.
example we create a Note that the 2:2
specifies the second
matrix below:
row and the 1:3
» x=[1,2,3;4,5,6;7,8,9] specifies which
x= columns of the row.
1 2 3 » y=x(2 : 2 , 1 : 3)
4 5 6 y=
7 8 9 4 5 6

July 28, 2010 Satish Chavan, DBIT 35


Matrices
 a vector x = [1 2 5 1]

x =
1 2 5 1
 a matrix
y = [1 2 3; 5 1 4; 3 2 -1]

y =
1 2 3
5 1 4
3 2 -1
 transpose p = x.’ p =
1
2
5
1

July 28, 2010 Satish Chavan, DBIT 36


y=
1 2 3
Matrices 5
3
1
2
4
-1

 x(i,j) subscription y=x(2,3)


y =
4

 whole row y=x(3,:)


y =
3 2 -1

 whole column y=x(:,2)


y =
2
1
July 28, 2010 Satish Chavan, DBIT 2 37
() Subscription
y=
v = [ 1 3 5 7 9]
1 3 2
3 4 5 v=
7 8 9 1 3 5 7 9
>> y(3) y = v(2)
ans = y=
7 3
>> y(8) p = v(2:4)
ans =
p= 3 5 7
5

July 28, 2010 Satish Chavan, DBIT 38


[ ] concatenation
x = [ zeros(1,3) ones(1,2) ]
x=
0 0 0 1 1

>>a= [1 2 ; 3 4]; >> a=[1 2 3;4 5 6];


>>b= [3 5 ; 6 7]; >> b=[6 7 8;9 1 2];
>> c=[a;b]
>> c=[b c]
c=
c=
1 2 3
3 5 1 2 4 5 6
6 7 3 4 6 7 8
9 1 2

July 28, 2010 Satish Chavan, DBIT 39


Matrix Math
 Matrix math
 Dimensions must agree
 Scalar math
 Same as usual
 Scalar / matrix math
 Scalar + matrix = [scalar + matrix(x, y)]
 Scalar * matrix = [scalar * matrix(x, y)]

July 28, 2010 Satish Chavan, DBIT 40


Reading Data from files
 MATLAB supports reading an entire file and creating a
matrix of the data with one statement.

>> load mydata.dat; % loads file into matrix.


% The matrix may be a scalar, a vector, or a
% matrix with multiple rows and columns. The
% matrix will be named mydata.
>> size (mydata) % size will return the number
% of rows and number of
% columns in the matrix
>> length (myvector) % length will return the total
% no. of elements in myvector
July 28, 2010 Satish Chavan, DBIT 41
Plotting with MATLAB
 MATLAB will plot one vector vs. another. The first
one will be treated as the abscissa (or x) vector
and the second as the ordinate (or y) vector. The
vectors have to be the same length.

 MATLAB will also plot a vector vs. its own index.


The index will be treated as the abscissa vector.
Given a vector “time” and a vector “dist” we could
say:
>> plot (time, dist) % plotting versus time
>> plot (dist) % plotting versus index

July 28, 2010 Satish Chavan, DBIT 42


Plotting with MATLAB
 There are commands in MATLAB to "annotate"
a plot to put on axis labels, titles, and legends.
For example:
To put a label on the axes we would use:
>> xlabel ('X-axis label')
>> ylabel ('Y-axis label')

% To put a title on the plot, we would use:


>> title ('Title of my plot')

July 28, 2010 Satish Chavan, DBIT 43


Plotting with MATLAB
 Vectors may be extracted from matrices. Normally, we
wish to plot one column vs. another. If we have a
matrix “mydata” with two columns, we can obtain the
columns as a vectors with the assignments as follows:

>> first_vector = mydata ( : , 1) ; % First column


>> second_vector = mydata ( : , 2) ; % Second one
% and we can plot the data
>> plot ( first_vector , second_vector )

July 28, 2010 Satish Chavan, DBIT 44


Matlab Graphics
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the
Sine Function')

July 28, 2010 Satish Chavan, DBIT 45


Multiple Graphs
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)
grid on

July 28, 2010 Satish Chavan, DBIT 46


Multiple Plots
t =
0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
subplot(2,2,1)
plot(t,y1)
subplot(2,2,2)
plot(t,y2)

July 28, 2010 Satish Chavan, DBIT 47


Random Numbers
x=rand(100,1);
stem(x);

hist(x,100)

July 28, 2010 Satish Chavan, DBIT 48


Graph Functions
(summary)
 plot linear plot
 stem discrete plot
 grid add grid lines
 xlabel add X-axis label
 ylabel add Y-axis label
 title add graph title
 subplot divide figure window
 figure create new figure window
 pause wait for user response

July 28, 2010 Satish Chavan, DBIT 49


Some Useful MATLAB
commands
 who List known variables
 whos List known variables plus their size
 help Ex: >> help sqrt Help on using sqrt
 lookfor Ex: >> lookfor sqrt Search for
keyword sqrt in m-files
 what Ex:>> what a: List MATLAB files in a:
 clear Clear all variables from work space
 clear x y Clear variables x and y from workspace
 clc Clear the command window

July 28, 2010 Satish Chavan, DBIT 50


Some Useful MATLAB commands
 what List all m-files in current directory
 dir List all files in current directory
 ls Same as dir
 type test Display test.m in command window
 delete test Delete test.m
 cd a: Change directory to a:
 chdir a: Same as cd
 pwd Show current directory
 which test Display current directory path to
test.m
July 28, 2010 Satish Chavan, DBIT 51
A Useless, But Interesting

 why In case you ever needed a


reason

July 28, 2010 Satish Chavan, DBIT 52


MATLAB Logical Functions
 MATLAB also supports some logical functions.
xor (exclusive or) Ex: xor (a, b)
Where a and b are logical expressions. The xor
operator evaluates to true if and only if one
expression is true and the other is false. True is
returned as 1, false as 0.
any (x) returns 1 if any element of x is nonzero
all (x) returns 1 if all elements of x are
nonzero
isnan (x) returns 1 at each NaN in x
isinf (x) returns 1 at each infinity in x
finite (x) returns 1 at each finite value in x
July 28, 2010 Satish Chavan, DBIT 53
MATLAB Display formats
 MATLAB supports 8 formats for outputting
numerical results.
format long 16 digits
format short e 5 digits plus exponent
format long e 16 digits plus exponent
format hex hexadecimal
format bank two decimal digits
format + positive, negative or zero
format rat rational number (215/6)
format short default display

July 28, 2010 Satish Chavan, DBIT 54


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
July 28, 2010 Satish Chavan, DBIT 55
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

July 28, 2010 Satish Chavan, DBIT 56


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

July 28, 2010 Satish Chavan, DBIT 57


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
July 28, 2010 Satish Chavan, DBIT 58
Generating Vectors from
functions
 zeros(M,N) x = zeros(1,3)
MxN matrix of zeros x =
 ones(M,N) 0 0 0

MxN matrix of ones


x = ones(1,3)
x =
1 1 1
 rand(M,N)
MxN matrix of uniformly x = rand(1,3)
x =
distributed random numbers
0.9501 0.2311 0.6068
on (0,1)

July 28, 2010 Satish Chavan, DBIT 59


() Subscription
y=
v = [ 1 3 5 7 9]
1 3 2
3 4 5 v=
7 8 9 1 3 5 7 9
>> y(3) y = v(2)
ans = y=
7 3
>> y(8) p = v(2:4)
ans =
p= 3 5 7
5

July 28, 2010 Satish Chavan, DBIT 60


General purpose
commands
 General information
 help -- M-file help, displayed at the command
line.
 helpwin -- M-file help, displayed in the help
browser.
 lookfor -- Search all M-files for keyword.
 demo -- Run demonstrations.
 Ver -- MATLAB, SIMULINK, and toolbox version
information.
 version -- MATLAB version information.

July 28, 2010 Satish Chavan, DBIT 61


General purpose
commands
 Managing the workspace
 who - List current variables.
 whos - List current variables, long form.
 workspace - Display Workspace Browser, a GUI
for managing the workspace.
 clear - Clear variables and functions from
memory.
 pack - Consolidate workspace memory.
 load - Load workspace variables from disk.
 save - Save workspace variables to disk.
 quit - Quit MATLAB session.

July 28, 2010 Satish Chavan, DBIT 62


MATLAB Script Files
 A MATLAB script file (Called an M-file) is a text (plain
ASCII) file that contains one or more MATLAB
commands and, optionally, comments.
 The file is saved with the extension ".m".
 When the filename (without the extension) is issued
as a command in MATLAB, the file is opened, read,
and the commands are executed as if input from the
keyboard. The result is similar to running a program
in C. The following slide is the contents of an M-file.
Note that there are no prompts (>>).

July 28, 2010 Satish Chavan, DBIT 63


MATLAB Script Files
% This is a MATLAB script file.
% It has been saved as “f13.m".
load f13.dat; %Load data file
voltage = d13( : , 4); %Extract volts vector
time = .005*[1:length(voltage)];%Create time vector
plot (time, voltage) %Plot volts vs time
xlabel ('Time in Seconds') % Label x axis
ylabel ('Voltage') % Label y axis
title ('Bike Strain Gage Voltage vs Time')
grid %Put a grid on graph
July 28, 2010 Satish Chavan, DBIT 64
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)

July 28, 2010 Satish Chavan, DBIT 65


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
July 28, 2010 Satish Chavan, DBIT 66
M-File Functions

Function name
• has the same constraints as variable name
• ONE function in ONE file
• 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 function on the current directory
• Check to see if the name is a function on the MATLAB search path

July 28, 2010 Satish Chavan, DBIT 67


Thank you

Questions Please…???

July 28, 2010 Satish Chavan, DBIT 68

You might also like