You are on page 1of 54

Introduction to Matlab

By
Mallikarjun.Talwar
Asst.prof E&CE Dept BKIT Bhalki
7/22/2014
Electronics and Communication
Dept BKIT Bhalki 1
Outline:

What is Matlab?
The Matlab Environment
Variables,Keywords,Vectors,Matrices
Operators
Functions
Plotting
Examples



7/22/2014
Electronics and Communication Dept BKIT
Bhalki 2
Introduction
MATLAB MATrix LABoratory
Initially developed by Cleve Moler a lecturer
in 1970s to help students learn linear
algebra.
It was later marketed and further developed
under Math Works Inc. (founded in 1984)
Created by The MathWorks, MATLAB
allows easy
matrix manipulation,
plotting of functions and data,

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 3

implementation of algorithms,

creation of user interfaces, and interfacing with
programs in other languages.

MATLAB is available for Windows, Macintosh
and UNIX systems. It is used by more than
one million people in industry and academia.

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 4

MATLAB is selected as a numerical analysis tool
over languages like C and Java because:
Very EASY programming language
Powerful graphics capabilities
Very sleek and interactive interface
Great for general scientific and engineering
computation
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 5
Why use Matlab?
Advantages:
It allows quick and easy coding in a very high-level
language.
Rich data types: Complex number, Three
dimensional matrix, structure, cell array, etc
Lots of nice functions and toolboxes
Lots of users: economists, mathematicians,
engineers,
High-quality graphics and visualization facilities are
available.
MATLAB M-files are completely portable across a
wide range of platforms.
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 6
What are we interested in?
Matlab is too broad for our purposes
The features we are going to require is


7/22/2014
Electronics and Communication Dept BKIT
Bhalki 7
Matlab
Command
Line
m-files
functions
mat-files
Command execution
like DOS command
window
Series of
Matlab
commands
Input
Output
capability
Data
storage/
loading
The Matlab Environment

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 8


7/22/2014
Electronics and Communication Dept BKIT
Bhalki 9
Command Window
type commands

Current Directory
View folders and m-files

Workspace
View program variables
Double click on a variable
to see it in the Array Editor

Command History
view past commands
save a whole session
using diary

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 10

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 11
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 12
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 13

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 14
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 15
Display Windows
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
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 16

who List known variables
whos List known variables plus their size
help help sqrt Help on using sqrt
lookfor lookfor sqrtSearch for keyword sqrt in m-files
what what a:List MATLAB files in a:
clear Clear all variables from work space
clear x y Clear variables x and y from work space
clc Clear the command window
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 17
The Help System

Search for appropriate function
>> lookfor keyword

Rapid help with syntax and function definition
>> help function

An advanced hyperlinked help system is launched by
>> helpdesk

Complete manuals (html & pdf)
http://www.mathworks.com/access/helpdesk/help/helpdesk.html
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 18

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 19

No need for types. i.e.,



All variables are created with double precision unless
specified and they are matrices.



After these statements, the variables are 1x1 matrices
with double precision

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 20
int a;
double b;
float c;
Example:
>>x=5;
>>x1=2;

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.

All variables are shown with
>> who
>> whos

Variables can be stored on file
>> save filename
>> clear
>> load filename

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 21

How do we assign a value to a variable?
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 22
>>> v1=3
v1 =
3
>>> i1=4
i1 =
4
>>> R=v1/i1
R =
0.7500
>>>
>>> whos
Name Size Bytes Class
R 1x1 8 double array
i1 1x1 8 double array
v1 1x1 8 double array
Grand total is 3 elements using 24 bytes
>>> who
Your variables are:
R i1 v1
>>>
ans Default variable name for results
pi Value of t
inf
NaN Not a number e.g. 0/0
i and j i = j =
eps Smallest incremental number
realmin The smallest usable positive real number
realmax The largest usable positive real number
MATLAB Special Variables

1
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 23
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 24
Vectors and Matrices
Vectors (arrays) are defined as
>> v = [1, 2, 4, 5]
>> w = [1; 2; 4; 5]



Matrices (2D arrays) defined similarly
>> A = [1,2,3;4,-5,6;5,-6,7]


How do we assign values to matrices ?
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 26
Columns separated by
space or a comma
Rows separated by
semi-colon
>>> A=[1 2 3;4 5 6;7 8 9]
A =
1 2 3
4 5 6
7 8 9
>>>
(
(
(

9 8 7
6 5 4
3 2 1
Long Array
t =1:10

t =
1 2 3 4 5 6 7 8 9 10
k =2:-0.5:-1

k =
2 1.5 1 0.5 0 -0.5 -1

B = [1:4; 5:8]

x =
1 2 3 4
5 6 7 8


7/22/2014
Electronics and Communication Dept BKIT
Bhalki 27
Generating Vectors from functions
zeros(M,N) MxN matrix of zeros



ones(M,N) MxN matrix of ones



rand(M,N) MxN matrix of uniformly
distributed random
numbers on (0,1)
x = zeros(1,3)
x =
0 0 0

x = ones(1,3)
x =
1 1 1

x = rand(1,3)
x =
0.9501 0.2311 0.6068
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 28
Matrix Index
The matrix indices must be positive integer
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 29
Given:
A(-2), A(0)

Error: ??? Subscript indices must either be real positive integers or logicals.

A(4,2)
Error: ??? Index exceeds matrix dimensions.
Concatenation of Matrices
x = [1 2], y = [4 5], z=[ 0 0]

A = [ x y]

1 2 4 5

B = [x ; y]

1 2
4 5


7/22/2014
Electronics and Communication Dept BKIT
Bhalki 30
C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent.
MATLAB Operators
+ addition
- subtraction
* multiplication
/ division
^ power
complex conjugate transpose

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 31
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)
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 32
Matrices Operations
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 33
Given A and B:
Addition Subtraction Product Transpose
Operators (Element by Element)


.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 34
The use of . Element Operation
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 35
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
A = [1 2 3; 5 1 4; 3 2 1]
A =
1 2 3
5 1 4
3 2 -1
y = A(3 ,:)

y=
3 4 -1
b = x .* y

b=
3 8 -3
c = x . / y

c=
0.33 0.5 -3
d = x .^2

d=
1 4 9
x = A(1,:)

x=
1 2 3
Some Elementary Functions
January 18, 2005 J. M. Sebeson - DeVry University 2005
Exponential.

exp - Exponential.
expm1 - Compute exp(x)-1 accurately.
log - Natural logarithm.
log1p - Compute log(1+x) accurately.
log10 - Common (base 10) logarithm.
log2 - Base 2 logarithm and dissect floating point number.
pow2 - Base 2 power and scale floating point number.
realpow - Power that will error out on complex result.
reallog - Natural logarithm of real number.
realsqrt - Square root of number greater than or equal to zero.
sqrt - Square root.
nthroot - Real n-th root of real numbers.
nextpow2 - Next higher power of 2.
4 Special functions
There are a number of special functions that provide
useful constants
pi = 3.14159265.
i or j = square root of -1
Inf = infinity
NaN = not a number

MATLAB has many built in functions which make it easy to perform a
variety of statistical operations
sum Sums the content of the variable passed
prod Multiplies the content of the variable passed
mean Calculates the mean of the variable passed
median Calculates the median of the variable passed
mode Calculates the Mode of the variable passed
std Calculates the standard deviation of the variable passed
sqrt Calculates the square root of the variable passed
max Finds the maximum of the data
min Finds the minimum of the data
size Gives the size of the variable passed

38
Polynomial example
0 10 4 5 . 0 2 . 1
2 3
= + + + x x x
>> x=[1.2,0.5,4,10]

x =

1.200 0.500 4.00 10.00

>> roots(x)

ans =

0.59014943179299 + 2.20679713205154i
0.59014943179299 - 2.20679713205154i
-1.59696553025265

Find polynomial roots:
function [A] = area(a,b,c)
s = (a+b+c)/2;
A = sqrt(s*(s-a)*(s-b)*(s-c));
To evaluate the area of a triangle with side of length 10, 15, 20:

>> Area = area(10,15,20)
Area =
72.6184

File area.m:
m-file example
Task:
Usage example:
Integration example
example with trapz function:

>> x = 0:0.5:10; y = 0.5 * sqrt(x) + x .* sin(x);
>> integral1 = trapz(x,y)
integral1 =
18.1655

Trapz:Trapezoidal numerical integration

}
|
.
|

\
|
+
10
0
) sin(
2
1
dx x x x Find the integral:
Representing signals
MATLAB represents signals as vectors:

>> x=[1,2,3,5,3,2,1]

x =

1 2 3 5 3 2 1

>> stem(x)

Waveform Generation
Basic Signals:
Unit impulse:
>> t = 0:0.01:1;
>> y = [zeros(1,50),1,zeros(1,50)];
>> plot(t,y);
Unit step:
>> y = [zeros(1,50),ones(1,51)];
>> plot(t,y);
Triangle:
>> t=-1:0.001:1;
>> y=tripuls(t);
>> plot (t,y);
Rectangle:
>> t=-1:0.001:1;
>> y=rectpuls(t);
>> plot (t,y);
Waveform Generation
Common Sequences:
Sawtooth:
>> fs = 10000;
>> t = 0:1/fs:1.5;
>> x = sawtooth(2*pi*50*t);
>> plot(t,x), axis([0 0.2 -1 1]);

Square wave:
>> t=0:20;
>> y=square(t);
>> plot(t,y)
Sinc function:
>> t = -5:0.1:5;
>> y = sinc(t);
>> plot(t,y)
Plotting
The plot function can be used in different ways:
>> plot(data)
>> plot(x, y)
>> plot(data, r.-)

In the last example the line style is defined
Colour: r, b, g, c, k, y etc.
Point style: . + * x o > etc.
Line style: - -- : .-
Type help plot for a full list of the options
45

A basic plot
>> x = [0:0.1:2*pi]
>> y = sin(x)
>> plot(x, y, r.-)
46
0 1 2 3 4 5 6 7
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 47
Some other functions that are helpful to create plots:

hold on and hold off
title
legend
axis
xlabel
ylabel
5 Plotting
>> x = [0:0.1:2*pi];
>> y = sin(x);

>> plot(x, y, 'b*-')

>> hold on

>> plot(x, y*2, r.-')

>> title('Sin Plots');

>> legend('sin(x)', '2*sin(x)');

>> axis([0 6.2 -2 2])

>> xlabel(x);

>> ylabel(y);

>> hold off
48
0 1 2 3 4 5 6
-2
-1.5
-1
-0.5
0
0.5
1
1.5
2
Sin Plots
x
y


sin(x)
2*sin(x)
Basic Task: Plot the function sin(x)
between 0x4
Create an x-array of 100 samples between 0
and 4.


Calculate sin(.) of the x-array


Plot the y-array


7/22/2014
Electronics and Communication Dept BKIT
Bhalki 49
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>plot(y)
0 10 20 30 40 50 60 70 80 90 100
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Plot the function e
-x/3
sin(x) between
0x4
Create an x-array of 100 samples between 0
and 4.

Calculate sin(.) of the x-array

Calculate e
-x/3
of the x-array

Multiply the arrays y and y1

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 50
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>y1=exp(-x/3);
>>y2=y*y1;
Plot the function e
-x/3
sin(x) between
0x4
Multiply the arrays y and y1 correctly

Plot the y2-array

7/22/2014
Electronics and Communication Dept BKIT
Bhalki 51
>>y2=y.*y1;
>>plot(y2)
0 10 20 30 40 50 60 70 80 90 100
-0.3
-0.2
-0.1
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Display Facilities
plot(.)



stem(.)
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 52

Example:
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>plot(y)
>>plot(x,y)


Example:
>>stem(y)
>>stem(x,y)

0 10 20 30 40 50 60 70 80 90 100
-0.3
-0.2
-0.1
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0 10 20 30 40 50 60 70 80 90 100
-0.3
-0.2
-0.1
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
Questions
?
?
?
?
?
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 53
Thank You
7/22/2014
Electronics and Communication Dept BKIT
Bhalki 54