You are on page 1of 40

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

A Training Session on

Fundamentals of MATLAB
in connection with the FDP on Digital Signal Processing Tools for Engineering Applications @ CET

12th November 2014

Resource Person : Dr. A. Ranjith Ram


Assistant Professor, ECE Dept.
Govt. College of Engineering Kannur
Cell : 94476 37667
e-mail
il : aranjithram@gmail.com
ji h
@
il
Objectives : Part I Getting familiarized with MATLAB
Part II Creating functions, 2-D and 3-D plots

PART I
Getting familiarized with MATLAB
90 Minutes (9:30 am 11:00 am)
am)

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Outline
Introduction MATLAB and Simulink
Toolboxes & Built-in Functions
Help & Documentation
Matrix Algebra
Polynomials and Roots
Trigonometric Functions
One Dimensional Plots
Developing and running MATLAB scripts
12 November 2014

Fundamentals of MATLAB

About MATLAB
MATLAB MATrix LABoratory a product by MathWorks Inc., USA
High Performance Computing Environment
Completely written using C Language
Unlike C, it is a Column Major Language
Available for both Windows and Linux
Version
V i : R2013a
R2013
or
8 1 0 604
8.1.0.604
R Release
2013 Year
a First half; b Second Half
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

The Company MathWorks


Founded in 1984 by Jack Little
(President) and Cleve Moler
(Chief Scientist) at Natick, USA
Jack Little

In addition to MATLAB,

Cleve Moler

MathWorks develops Simulink,


a product for simulating linear
and nonlinear dynamic systems
Website : www.mathworks.in
12 November 2014

Fundamentals of MATLAB

MATLAB & Simulink


MATLAB uses an algorithmic approach for programming and is a CUI
based computing environment
Simulink, on the other hand, uses block diagram based approach and
hence, is a GUI based one.
One can say that Simulink is built on MATLAB
However,, one has to purchase
p
Simulink alongg with MATLAB,, if he/she
requires Simulink
MATLAB functions resides in the respective Toolboxes
Simulink boxes are residing in the respective Blocksets
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Where we fit MATLAB ?


MATLAB
High Level
Languages such as
Pascal, C, C++ etc.
Assembly Language

Machine Language
12 November 2014

Fundamentals of MATLAB

First few points


Everything in MATLAB is a matrix !
MATLAB is an interpreted language, not a compiler based one
MATLAB does not need any variable declarations
MATLAB does not require any dimension statements
MATLAB has no packaging
MATLAB does not need any storage allocation
MATLAB does not require any pointers
Programs can be run step by step, with full access to all variables,
functions etc.
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

How to Open
Double Clicking the emblem
Version

Product

Company

12 November 2014

Fundamentals of MATLAB

MATLAB Desktop

Workspace
Current
Folder

Command
Window
Command
History

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

10

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Using Command Window


a = 1
a = 1;
b = (pi/180) * theta
theta should be defined !
c = a + b;
d = a b;
b
Clearing commands
clc;
clear;
12 November 2014

Fundamentals of MATLAB

11

Why it is different from C ?


No need for defining the data types, i.e.,
int a;
double b;
float c;

All variables are created with double precision unless specified otherwise
Example:
>> x = 5;
>> x1 = 2;

After these statements, these variables are 1 x 1 matrices with double


precision
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

12

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Creating a Row Vector


r

= [
[1 2 3 4]
] or [
[1,
, 2,
, 3,
, 4]
]
Delimiter is a space or comma
Enclosed in square braces
MATLAB takes the above as
r = [ 1 2 3 4 ]
= [1:10] or 1:10
MATLAB takes the above as
n = [ 1 2 3 4 5 6 7 8 9 10 ]
= [3:2:15] or 3:2:15
MATLAB takes the above as
k = [ 3 5 7 9 11 13 15 ]

12 November 2014

Fundamentals of MATLAB

13

Creating a Row Vector (Contd)


Contd)
Suppose
pp
we want N number of data points
p
in the interval (x1,
( , x2))
The previous method fails here as one has to compute the step size
explicitly
linspace linearly spaced vector take care of this situation in
MATLAB
linspace(X1, X2) generates a row vector of 100 linearly
equally spaced points between X1 and X2.
linspace(X1,
linspace(X1 X2,
X2 N) generates N points between X1 and
X2.
For N = 1, linspace returns X2
linspace is useful in many signal processing and plotting situations.
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

14

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Creating a Column Vector


c

= [
[1;
; 2;
; 3;
; 4]
]
Delimiter is a semicolon
Enclosed in square braces
MATLAB takes the above as
c=[1
2
3
4 ]
Transposing operation : using
r = 2:3:10 ;
c = r ;
12 November 2014

Fundamentals of MATLAB

15

Creating an M x N Matrix
m

m
a
b
c

= [
[1 2 3;
; 4 5 6;
; 7 8 9];
];
Delimiters are spaces and semicolons
Enclosed in square braces
MATLAB takes the above as
c=[1 2 3
4 5 6
7 8 9]
= [1:3; 4:6; 7:9];
= [1; 2; 3; 4];
= [5; 7; 8; 9]
= [a b];

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

16

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Variable Classes or Data Types


MATLAB supports several classes of variables (or data types)
Numeric
Character
Logical
Structure
Cell array

12 November 2014

Fundamentals of MATLAB

17

Data Types (Contd)


Contd)

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

18

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

MATLAB Toolboxes

Aerospace Toolbox
Bioinformatics Toolbox
Communications System Toolbox
Computer Vision System Toolbox
Control System Toolbox
Curve Fitting Toolbox
Data Acquisition Toolbox
Database Toolbox
DSP S
System T
Toolbox
lb
Econometrics Toolbox
Financial Toolbox
Fuzzy Logic Toolbox
Image Acquisition Toolbox

12 November 2014

Image Processing Toolbox


Instrument Control Toolbox
Mapping Toolbox
Model Predictive Control Toolbox
Model-Based Calibration Toolbox
Neural Network Toolbox
Optimization Toolbox
Parallel Computing Toolbox
P i l Differential
Partial
Diff
i l Equation
E
i Toolbox
T lb
Phased Array System Toolbox
RF Toolbox
Robust Control Toolbox
Signal Processing Toolbox

Fundamentals of MATLAB

19

Some BuiltBuilt-in Functions

sin()
cos()
()
inv()
eye()
rand()
ones()
zeros()
size()
l
length()
h()
max()
min()
fliplr()
flipud()

12 November 2014

plot()
stem()
t ()
surf()
mesh()
fft()
abs()
eig()
rank()
ceil()
il()
round()
sum()
prod()
linspace()

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

20

10

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Help / Documentation
help
p function_name
_
or doc function_name
_
Help Menu

Search

12 November 2014

Fundamentals of MATLAB

21

Matrix Addition & Subtraction


Matrix addition : +
a = [1 2 3 4];
b = [5 6 7 8];
c = a + b
yields c = [6 8 10 12]
Matrix subtraction :
a = [7 2 6 9];
b = [5 6 7 8];
c = a - b
yields c = [2 -4 -1 1]
Both the matrices should be of the same dimensions.
Equivalent to addition and subtraction of two signals
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

22

11

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Matrix Multiplication
Matrix multiplication : *
a = [1 2 3 4; 3 1 2 4];
b = [3 1; 1 2; 0 1; 2 3];
c = a * b
yields c = [ 13 20
18 19 ]
Both a & b should be conformable to multiplication
a should be of dimension M x N and b should be of N x K
The result will be of M x K dimension
Multiplication by a scalar is also done using *
The function equivalent to * is mtimes()
c = mtimes(a, b)
12 November 2014

Fundamentals of MATLAB

23

Signal Product
Signal multiplication is done using .*
.*
* will
ill compute the
h element-by-element
l
b l
product
d
a = 1:5;
b = 2:6;
c = a .* b
will yield c = [ 2 6 12 20 30 ]
Matrix dimensions must match.
Will output a signal of same dimension
Is useful is many signal processing operations
The function equivalent to .* is times()
Check:
pow = a .* a; and pow = a .^ 2;
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

24

12

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Matrix Division (?)


1.

2.

Matrix division using /


a = [1 2 3; 0 1 2; 3 0 4];
b = [3 0 1; 1 2 0; 0 1 3];
c = a / b
yields c = [0.1579
0.5263
-0.0526
0.1579
1.1579
-0.4737
a / b computes
p
a * inv(b)
Matrix division using \
a \ b computes inv(a) * b
Find the inverse of a using \
a \ eye(size(a))

12 November 2014

Fundamentals of MATLAB

0.9474
0.6842
0.9474]

25

Matrix Indexing and Addressing


In MATLAB, the indexing is from 1 to N, unlike from 0 to N1 in DSP
th
theory
or C Language
L
This practicality is to be taken care of when the an algorithm in
theoretical DSP is getting implemented using MATLAB
normal braces ( ) are used for addressing elements of a matrix
temp(5,10) selects the element in the 5th row and 10th column of the
matrix temp
marks(:,3) selects the third column of the matrix marks
marks(2,:) selects the second raw of the matrix marks
lena(:,:,2) selects the green component of the colour image lena
face(20:50,30:60,:) will select a rectangular region of the
colour image face
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

26

13

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Other Methods of Indexing


In MATLAB, indexing has more advanced features
One can use a vector for indexing another vector.
For example,
>> a = [ 10 12 31 24 53 36];
>> b = [2 4 6];
>> a(b)
will yield
>> ans = 12 24 36
This is a powerful indexing method in MATLAB
Another type of indexing is logical indexing, which would be covered
later, in Part-II of this training
12 November 2014

Fundamentals of MATLAB

27

Functions for Matrices

inv(a) inverse of the matrix a


eye(N) identity matrix of dimension
dimension, N x N
rand(N) a square matrix of dimension N x N
ones(N) and zeros(N) square matrices of 0s & 1s
size(a) and length(a) length = max(size(a))
max() and min() max & min of the columns
fliplr() and flipud() flipping left-right & up-down
eig(a)
g
eigen
g values of the matrix a
rank(a) rank of the matrix a
sum(a) sum of the elements of a
prod(a) product of the elements of a
power() matrix power

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

28

14

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Data Input
Generally there are three ways of inputting data into MATLAB
directly entering in the command line
from memory
read an excel file
read a speech file
read an image file
from I/O devices
input from a sensor
input from a microphone
input from a camera
12 November 2014

Fundamentals of MATLAB

29

Data Input Examples


fc = input('Enter the carrier frequency: ');
x = xlsread(table.xlsx');
wavread(aud.wav);
imread(lena.jpg);
S=load(filemname);
import menu import a file

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

30

15

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Data Output
Generally there are three ways of outputting data from MATLAB
directly flashing to command line
to memory
write an excel file
write a speech file
write an image file
to I/O devices
output to a DAC
output to a loudspeaker
output to a display
12 November 2014

Fundamentals of MATLAB

31

Data Output Examples


sprintf(The bandwidth is %d', bw) or display(bw)
fid = fopen('exp.txt','w');
f
('
' ' ')
fprintf(fid,'%6.2f

%12.8f\n',y);

fclose(fid);
xlswrite(t.xlsx,m)
wavwrite(s,fs,au.wav)
( , ,
) / sound(s,fs)
( , )
imwrite(y,img.jpg) / imshow(y)
save(filename, var)
save menu
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

32

16

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Characters and Meaning

; suppressing output in the command window


= assignment
+ addition
- subtraction
* matrix product
/ post multiply with inverse
\ pre multiply with inverse
< less than
> greater than
~ logical not
& logical and
| logical or

12 November 2014

Fundamentals of MATLAB

33

Characters and Meaning (Contd)


Contd)

. element wise operation, decimal point, structure field access


.. parent directory
continuation
: range
[ ] matrix entry
( ) addressing array elements, function
{ } cell array addressing
% commentingg
^ power
string entity
complex conjugate transpose
@ function handle

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

34

17

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Reserved Characters / Words


i imaginary notation
j

do

pi 3.14..
Inf infinity
NaN not a number
eps spacing of floating point numbers
who prints variables in work space
why answers to such a question. Do chat with MATLAB !
beep produces a beep sound
12 November 2014

Fundamentals of MATLAB

35

Roots of a Polynomial
roots(C) computes the roots of the polynomial whose coefficients
are the elements of the vector C
If C has N+1 components, the polynomial is C(1)*X^N + ... +
C(N)*X + C(N+1).
C = [1

-3

2 ];

r = roots(C)
yields r = [-2

1]

p = poly(r) converts the roots to its polynomial


yields p = [1
12 November 2014

-3

2]

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

36

18

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

One Dimensional Plots


plot(x, y)
plots
l t vector
t y versus vector
t x
If x or y is a matrix, then the vector is plotted versus the rows or
columns of the matrix, whichever line up
plot(y) plots the columns of y versus their index
if y is complex, plot(y) is equivalent to plot(real(y), imag(y))
in all other uses of plot, the imaginary part is ignored
stem()
() pplots a signal
g in a sampled
p fashion
bar() plots a signal in bar form
stairs() plots a signal in staircase form
scatter() plots in the form of scatter diagram
12 November 2014

Fundamentals of MATLAB

37

Plotting Trigonometric Functions


The range of the independent variable should be defined first
All the parameters appearing in the function also should be defined
t = 1 : 200;

10
8

w = 0.2;

6
4

x = 10*sin(w*t);
plot(t x);
plot(t,
This yields an output figure :

2
0
-2
-4
-6
-8
-10

12 November 2014

20

40

60

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

80

100

120

140

160

180

200

38

19

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Plotting More features

Choosing colour and line width


Addi titl
Adding
title, x-label
l b l & y-label,
l b l grid
id lines
li
andd legends
l
d
Choice of range of the independent and dependent variable axes
t=1:200; w=0.2;
x=10*sin(w*t);
plot(t, x, r, LineWidth, 2);
grid on;
axis([50 150 -10
10 +10])
title(The Sine Wave);
xlabel(Sampling Instants);
ylabel(Amplitude);
legend(Sin(wt))

12 November 2014

Fundamentals of MATLAB

39

When to Create a Script File


t = 1 : 1 : 200;
f = 0.2;
0 2;
C
Command
d li
line based
b d computation
t ti has
h
its own limitations
x = 6*cos(2*pi*f*t);
plot(n, x, r);
title(The Sine Wave);
xlabel(Sampling Instants);
ylabel(Amplitude);
If one has to find/plot a function after changing the value of one of the
variable, he/she has to execute all the subsequent commands one by one
At this point, script files or m-files need to be created
It is created using an editor which is having all the features like cut/copypaste, undo, indent, insert, save as, etc.
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

40

20

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Creating a Script File


Click on the New Script menu on the MATLAB Desktop

12 November 2014

Fundamentals of MATLAB

41

Developing a script file


Enter all the instructions line-by-line in the editor
Or,
O S
Select
l t th
the group off commands
d from
f
the
th commandd history
hi t
andd righti ht
click on the selection to create script

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

42

21

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Running a Script File


Click on the Run Button on the Editor Menu

12 November 2014

Fundamentals of MATLAB

43

Multiple Plots in a Window


t = 1 : 1 : 200;
f = 0.2;
0 2;
x1 = 6*cos(2*pi*f*t);
x2 = 4*sin(2*pi*2*f*t);
subplot(2 2 1)
plot(n, x1, r, LineWidth, 2);
Subplot(2 2 2)
plot(n, x2, b,
b , LineWidth,
LineWidth , 2);
Subplot(2 2 3)
plot(n, x1.^2, g, LineWidth, 2);
Subplot(2 2 2)
plot(n, x2.^2, k, LineWidth, 2);
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

44

22

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Plots in Different Windows


t = 1 : 1 : 200;
f = 0.2;
0 2;
x1 = 6*cos(2*pi*f*t);
x2 = 4*sin(2*pi*2*f*t);
figure(1)
plot(n, x1, r, LineWidth, 2);
figure(2)
plot(n, x2, b,
b , LineWidth,
LineWidth , 2);
figure(3)
plot(n, x1.^2, g, LineWidth, 2);
figure(4)
plot(n, x2.^2, k, LineWidth, 2);
12 November 2014

Fundamentals of MATLAB

45

Plots on the Same Axes


t = 1 : 1 : 200;
f = 0.2;
0 2;
x1 = 6*cos(2*pi*f*t);
x2 = 4*sin(2*pi*2*f*t);
plot(n, x1, r, LineWidth, 2);
hold on;
plot(n, x2, b, LineWidth, 2);
hold on;
plot(n, x1.^2, g, LineWidth, 2);
hold on;
plot(n, x2.^2, k, LineWidth, 2);
hold off;
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

46

23

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Exercise
1)

Plot the function x(t) = eat

2)

Plot the function x(t) = 1 e at

3)

Plot the function x(t) = 6 Sin(at) 4 Cos(bt)

4)

Plot the function x(t) = Cos(bt) eat

5)

Plot the function f(x) = sinc(x)

6)

Pl the
Plot
h ffunction
i f(x)
f( ) = (1/2)
(1/2 ) e (x )

7)

Plot the function x(n) = ean

8)

Plot the function x(n) = 6 Sin(an) 4 Cos(bn)

12 November 2014

2 / 22

Fundamentals of MATLAB

47

Part I : Summary
Familiarized with MATLAB desktop, toolboxes, variable classes and
some built-in functions
Performed simple computations using the command prompt, reviewed
fundamentals of linear algebra using MATLAB
Differentiated the matrix product from signal product
Studied how to seek help in the command prompt and how to use the
help menu
Learnt the various methods of data input
p and output
p
Computed the roots of a polynomial and obtained the polynomial from a
root set
Learnt how to plot one dimensional (1-D) curves
Studied how to create and run the MATLAB script files
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

48

24

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

PART II
Creating functions, 22-D and 33--D plots
90 Minutes
Mi
((11
(11:15
11 15 am 12:45
11:15
12 45 pm))

12 November 2014

Fundamentals of MATLAB

49

Outline
Logical operations and logical indexing
The for loop and while loop
Commenting and publishing MATLAB script files
Standard AM and FM Simulation
Computing the execution time
Developing user-defined functions
Global variables, current directory & path
Plotting 2-D and 3-D figures in MATLAB
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

50

25

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Logical Operations
Logical operations are :
==
>
<
>=
<=
~=
&
|

12 November 2014

or

eq

or
or
or

ge
le
ne

Fundamentals of MATLAB

51

Logical Indexing
One can use logical indexing to extract portions of data according to a
logical criterion.
Comparisons using relational operators such as < and == return a logical
array.
Eg., id = mark >= 48;
creates a logical variable id of the same size as mark
One can use a logical variable as an index to any other variable The
result will be the array elements where the index is true
t
topranked
k d = mark(id);
k(id)
Note that the result of logical indexing will be a smaller array (possibly
even empty if the index contains no true values).
It is therefore important to be careful to keep dimensions consistent when
indexing to multiple variables.
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

52

26

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

The for Loop


for i=1:1:10
pow = i*i
end
for should always be closed with end
for nested for loops, there should be sufficient number of ends
for i=1:1:20
for j=1:1:10
prod = i
i*j
j
end
end
Default increment of the index is unity
The drawback of using for loops in MATLAB is the computational delay
12 November 2014

Fundamentals of MATLAB

53

if - else
if else also should be closed with end
for i=0:1:10
if rem(i,2) ~= 0
odd = i
else
even = i
end
end

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

54

27

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

While
Performs a group of operations when a condition is satisfied
a = 1
1
while length(a) < 10
1 1
a = [0 a] + [a 0]
1 2 1
end
1 3 3 1
1 4 6 4 1
produces the Pascals Triangle :
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
12 November 2014

Fundamentals of MATLAB

55

Break
Is used to terminate the iterations of a loop.
for i=1:1:100
pow = i*i
if pow > 100
break;
end
end

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

56

28

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Making the script useruser-friendly


By inserting comments at appropriate positions in the script
Commenting in MATLAB is by putting %
There is no need to enclose the comment inside two %s
All the text portion to the right side of a % until a line feed will be
treated as a comment
The commented portion would be automatically displayed in green
fonts in the MATLAB editor
The process of commenting not only for making the script user-friendly,
but also to serve for additional features on publishing the script.
12 November 2014

Fundamentals of MATLAB

57

Publishing a MATLAB script


Publishingg :

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

58

29

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Publishing Options
Output file format

Appropriate placing of %% effects the generation of section titles and


table of content in the published file.
12 November 2014

Fundamentals of MATLAB

59

Standard AM A typical MATLAB program


Equation : v(t) = Vc [1 + kavm(t)] cos (2fct)
Code segment :
t = 1:100;
f1 = 0.02;
f2 = 0.5;
vm = cos(2*pi*f1*t);
vc = cos(2*pi*f2*t);
sam = (1+0.8*vm).*vc;

%
%
%
%
%
%

Sampling instants
Baseband frequency
Carrier frequency
Baseband Signal
Carrier Signal
Standard AM

(Go to the Script File)


12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

60

30

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

FM Another example
Equation : v = V cos (c t + mf sin m t)
Code segment :
t = 1:200;
% Sampling instants
% Baseband frequency
f1 = 0.01;
f2 = 0.1;
% Carrier frequency
mf = 4;
% Modulation Index
vm = cos(2*pi*f1*t);
% Baseband Signal
vc = cos(2*pi*f2*t);
% Carrier Wave
fm = cos(2*pi*f2*t+mf*sin(2*pi*f1*t)); % FM
(Go to the Script File)
12 November 2014

Fundamentals of MATLAB

61

The Execution Time


Avoid using for loops as much as possible since it consumes time. If
l i l indexing
logical
i d i is
i used,
d the
th code
d becomes
b
faster
f t !
tic & toc functions work together to measure elapsed time.
toc, by itself, displays the elapsed time, in seconds, since the most
recent execution of the tic command.
T = toc saves the elapsed time in T as a double scalar.
toc(TSTART) measures the time elapsed since the tic command that
generated TSTART.
Example code is
>> tic
>> E = sum(abs(X).^2)/8;
>> toc
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

62

31

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Deliberate Delay Pause


One can deliberately delay the computation by inserting a pause
commandd iin MATLAB
For example, pause(5) delays the execution of the next command by
5 seconds
Example code is
>> tic
(
( )
)/ ;
>> E = sum(abs(X).^2)/8;
>> delay(5)
>> toc

12 November 2014

Fundamentals of MATLAB

63

Creating UserUser-defined Functions


One can modularize the code by creating his/her own functions in
MATLAB
A main script file may call these functions by passing appropriate
arguments to them.
All the concepts like arguments, local and global variables etc.,
concerned with C programming is applicable here also.
Hence at the function call
call, arguments are passed to the function
The function performs the necessary computation and returns values to
the calling program
The returned values are used in the main script
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

64

32

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Form of MATLAB Functions


The first command line should be of the form
function [v1 v2] = funct_name(a1, a2, ..., an)
v1 & v2

return values

funct_name name given to the function


a1, a2, ..., an arguments passed
Care should be taken : The script file itself should be named with
funct_name.m and it should reside in the current directory
Then one can use the user-defined function, func_name by typing
[p q] = func_name(i, j, l, ... n)
12 November 2014

Fundamentals of MATLAB

65

More about MATLAB functions


If the function is not in the current directory, one can Set Path for calling
the function
The comments inserted in the beginning of MATLAB function script
bear additional information than simple comment lines
They serve as the information to be displayed on the screen when the
user seeks help
First few lines of comments until two line breaks will be thrown for
display on help
This is how comment lines are placed in a MATLAB function
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

66

33

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Local & Global Variables


function g = game(p,q,r,s)
global a b;
% global variables
t=p*q/a;
u=r*s/b;
g = t.^2 + u.^2; % return value
If not defined as global, all the variables are local to the function
Interestingly, one can note that the local variables will not be displayed
in the workspace
p
Unlike C, the functions are not to be written in the same file as the main
program
A function can also be passed as an argument to another function
In this case, @funct_name is to be used as the argument
12 November 2014

Fundamentals of MATLAB

67

Current Directory
Current
Directory

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

68

34

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Setting Path
Settingg a ppath

12 November 2014

Fundamentals of MATLAB

69

2-D and 33--D plots in MATLAB


One can have higher dimensional plots in MATLAB using appropriate
functions
For this, the first task is to select the two dimensional data points
The corresponding task in 1-D case was achieved by using
t = 1 : 200

or

t = linspace(1,200,200)
Here t would serve as the index for the placement of 1-D samples
In 2-D, an extended spatial arrangement is required to initialize a plot
The MATLAB function meshgrid will serve this purpose
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

70

35

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Making data points for 22--D plots


The meshgrid function converts vectors of points into matrices that
can representt a grid
id off points
i t in
i the
th x-y plane
l

>> x = 1:7;
>> y = 2:2:12;
>> [X,Y] = meshgrid(x,y);

x : 1 x 7 vector
y : 1 x 6 vector
Grid is formed with 6 x 7 points
Here X contains the x coordinates of all points in the 6-by-7 grid and Y
contains the corresponding y coordinates.
These matrices of coordinates can be used in calculations, interpolation
of scattered data and visualization.
12 November 2014

Fundamentals of MATLAB

71

Mesh Grid
(1 2)
(1,2)

(4,2)

(7,8)

(1,8)

(1,12)

12 November 2014

(7,2)

(4,12)

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

(7,12)

72

36

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Two Dimensional Plots


contour(z)
plot of matrix z treating the values in z as heights above a plane
are the level curves of z for some values v. The values v are chosen
automatically
contour(x, y, z) x and y specify the (x, y) coordinates of the
surface
fill(x, y, c)
fills the 2-D polygon defined by vectors x and y with the color
specified
ifi d by
b c
The vertices of the polygon are specified by pairs of components of
x and y
c is a single character string chosen from the list 'r', 'g',
'b', 'c', 'm', 'y', 'w', 'k'.
12 November 2014

Fundamentals of MATLAB

73

2-D Plot Example contour


[x y] = meshgrid(-3:0.1:+3, -3:0.1:+3);
contour(x y x ^2 + y.^2);
contour(x,y,x.^2
y ^2);
3
axis square
2

This yields an output figure :


-1

-2

-3
-3

12 November 2014

-2

-1

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

74

37

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Three Dimensional Plots


plot3(x, y, z)
if x, y, andd z are vectors,
t
it plots
l t a line
li in
i 3D space through
th
h the
th
points whose coordinates are the elements of x, y and z.
if x, y, and z are matrices, it plots several lines obtained from the
columns of x, y and z.
contour3(x, y, z)
3D contour plot
mesh(x, y, z)
plots the colored parametric mesh defined by the arguments
surf(x, y, z)
plots the colored parametric surface defined by the arguments
colour is proportional to the height of the surface
12 November 2014

Fundamentals of MATLAB

75

3-D Plot Example plot3


t=-2:0.01:2;
Plot3(cos(2*pi*t),sin(2*pi*t),t);
2

This yields an output figure :


-1

-2
1
0.5

1
0.5

-0.5

-0.5
-1

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

-1

76

38

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

3-D Plot Example mesh


[x y] = meshgrid(-2:0.1:2,-2:0.1:2);
z=x.^2-y.^2;
Saddle Point
mesh(x,y,z);
4

This yields an output figure :

-2
2

-4
2
1

2
1

-1

-1
-2

12 November 2014

-2

Fundamentals of MATLAB

77

3-D Plot Example surf


[z theta] = meshgrid(-1:0.1:1, (0:0.1:2)*pi);
x=sqrt(1-z.^2).*cos(theta);
y=sqrt(1-z.^2).*sin(theta);
1
surf(x,y,z);
0.5
axis square
0

This yields an output figure :

-0.5

-1
1
0.5

1
0.5

-0.5

-0.5
-1

12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

-1

78

39

Fundamentals of MATLAB : A Session on FDP @ CET Cheemeni

12/11/2014

Part II : Summary
Studied about logical operations and logical indexing
Familiarized with for loop, while loop and break
Studied how to insert comments and to publish a MATLAB script
Simulated standard AM and FM
Computed the execution time and learnt to introduce delay
Studied how to create user-defined functions
Earned the notion of global variables, current directory & path
Learnt how to plot 2-D and 3-D figures in MATLAB
12 November 2014

Fundamentals of MATLAB

79

Thanks

aranjithram@gmail.com
12 November 2014

Fundamentals of MATLAB

Dr. A. Ranjith Ram aranjithram@gmail.com

80

40

You might also like