Você está na página 1de 79

M

E
S

S
K
,

E
C
E
Introduction to MATLAB
f
o
t
p
e
and Simulink ., D
A
.
Presented by:
B
Ravikiran B. A.
n
a
Asst. Professor, Dept of ECE ir
k
i
KSSEM
v
a
R
y
b
d
e
t
a
e
r
C

Introduction to MATLAB and Simulink

What is

M
E
S

MATLAB?

S
K
,

The Language of Technical Computing

f
o
t

Numerical Programming Environment


MATLAB - MATrix LABoratory

,
.
A

High-Level Interpreted Language


Uses:
Analyze Data

n
a
ir

.
B

E
C
E

p
e
D

k
i
Create Models and
vApplications.
a
R
Multidisciplinary
Applications
y
b
d
e
t
a
e
r
C
Develop Algorithms

K. S. School of Engineering and Management

Introduction to MATLAB and Simulink

What Can I Do with MATLAB?

M
E
S

S
K
,

E
C
E

Acquire and Analyze Data from different sources


Data from Measuring and Sensing Instruments
Recorded Data (Spreadsheets, text files, images, audio files, etc)

f
o
t

Analyze Data using different tools

p
e
D

,
.
Develop Functions and Algorithms
A
.
B plots, etc
Visualize Data in terms ofngraphs,
a
r
i
Simulink is used to Develop
Models and Applications
k
i
v
Deploy Code as a
Standalone
Applications
R
y
b
d
e
t
a
e
r
C
K. S. School of Engineering and Management

Introduction to MATLAB and Simulink

M
E
S

Where Can I use MATLAB?


MATLAB is a Multi-discipinary Tool

f
o
t

S
K
,

E
C
E

Can be used in any Numerical Computation Application

p
e
D

,
.
ACurve fitting, Optimization)
Mathematics(Symbolic Math, Statistics,
.
Communications & Signal Processing
(RF, LTE, DSP, Wavelets)
B
n Computer Vision)
Machine Vision (Image Processing,
a
r
i
Control Systems (Fuzzy
Logic, Predictive Control, Neural Networks)
k
i
v and Distributed Computing
Parallel Computing
a
R
Statistics and
Curve Fitting
y
Computational
Finance ( Financial, Econometrics, Trading, etc)
b
d
Instrument Control, Vehicle Networks (CAN) , Aerospace
e
t

90+ Toolboxes in multiple fields

a
e
r

K. S. School of Engineering and Management

Introduction to MATLAB and Simulink

M
E
S

Where can I use Simulink?

S
K
,

E
C
E

Simulink is a Block Diagram Environment for Multidomain

simulation and Model-Based Design.


f
o
Build, Simulate and Analyze models using tBlocks.
p
e
Connect to External Hardware (FPGA,
,. D DSP Processors,
Microprocessor, Microcontroller,Aetc) and run the models there
.
B
directly.

n
a
ir

Simscape (Physical Systems Mechanical, Electrical, Hydraulic, etc)

k
i
v

SimMechanics ( Robotics, Vehicle Suspensions, HIL system support)

a
R
y (Hydraulic Components)
SimHydraulics
b
SimRF
(RF Systems)
d
e
tSimPowerSystems (Electrical Power Systems)
a
e

SimDriveline (1-D Driveline System Simulation)

Cr

SimElectronics (Motors, Drives, Sensors, Actuators, etc)


K. S. School of Engineering and Management

Introduction to MATLAB and Simulink

Why bother using them?

M
E
S

S
K
,

E
C
E
perform mathematical operations very efficiently.
f
o
t
High speed of computation.
p
e
Easy to learn and write MATLAB code.
,. D
A
Tons of built-in code and freely. available
User-submitted code.
B
n
a
r
i
Simulink uses Block
approach with Drag-And-Drop.
k
i
v
a
Easy to use and
implement models.
R
y
No hasslebdeployment of same model to multiple devices
d
e
t
a
e
r
C
MATLAB has optimized mathematical algorithms which

K. S. School of Engineering and Management

M
E
S

S
K
,

f
o
t

MATLAB
n
a
ir

k
i
v

a
R
y

b
d

e
r
C

e
t
a

.
B

,
.
A

p
e
D

E
C
E

Introduction to MATLAB and Simulink

M
E
S

The MATLAB Screen

S
K
,

Command Window

f
o
t

Type commands

Current Directory
View folders and m-files

n
a
ir

Workspace
View program variables

.
B

,
.
A

E
C
E

p
e
D

k
i
v

Double click on a variable

to see it in the Array Editor

a
R
Command History
y
b
View Past Commands
Save a d
whole session
e
t Diary
using
a
e
r
C

K. S. School of Engineering and Management

Introduction to MATLAB and Simulink

Matrices Matrices Everywhere

M
E
S

S
K
,

E
C
E

MATLAB works primarily (almost exclusively) with matrices.

f
o
t

MATLAB functions are optimized to handle matrix operations.

p
e
D

MATLAB can handle upto 13-dimensional matrices.

,
.
A

Loops can be vectorized for faster operations.

n
a
ir

.
B

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

Introduction to MATLAB and Simulink

M
E
S

Matrices - Arrays and Vectors

S
K
,

E
C
E

Matrix is a one- or multi-dimensional array of elements.

f
o
t

Elements can be numerical, variables or string elements.

p
e
D

By default, MATLAB stores numbers as double precision.

,
.
A

ALL data in MATLAB are viewed as matrices.

.
B

Matrices can be:


Created Manually by User
Generated by MATLAB Functions
Imported from stored databases or files

n
a
ir

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

10

Introduction to MATLAB and Simulink

M
E
S

Array Declaration

S
K
,

E
C
E

Unlike C, MATLAB is an interpreted language. So, there is no

need for Type Declaration.


f
o
A single variable is interpreted as 1x1 matrix.
pt

e
D
.,

>> a = 5
a=

n
a
ir

A
.
B

Arrays are represented as a series of numbers (or characters)

k
within square brackets,
with or without a comma separating the
i
v
values.
Ra
y
b
d

>> b = [1 2 3 4 5]

e
r
C

e
t
a

b=

% Percentage Symbol indicates Comment

K. S. School of Engineering and Management

11

Introduction to MATLAB and Simulink

Multidimensional Arrays

M
E
S

S
K
,

E
C
brackets, with the ; (semicolon) operator indicating
end of a
E
f
row.
o
t
p
>> c = [1 2 3 ; 4 5 6 ; 7 8 9 ; 10 11 12]
e
D
,
.
A
c=
.
B
1 2 3
n
4 5 6
a
r
i
7 8 i9k
v12
10 11
a
R
c is now a 2-D
array with 4 rows and 3 columns
y
b
d
e
t
a
e : Variable names are case sensitive and can be upto 31 characters long, and have
Note
r
Cto start with an alphabet.
2-D or Multidimensional Arrays are represented within square

K. S. School of Engineering and Management

12

Introduction to MATLAB and Simulink

M
E
S

Strings

S
K
,

Character strings are treated as arrays too.


>> name = 'Ravi

f
o
t

is the same as
>> name = [R a v i]

And gives the output:


name =

n
a
ir

Ravi

.
B

,
.
A

E
C
E

p
e
D

k
i
v

Strings and Characters


are both declared within SINGLE
R
quotes (b)y

d
e
at

e
r
C

K. S. School of Engineering and Management

13

Introduction to MATLAB and Simulink

M
E
S

Array Indices

S
K
,

E
C
E

Unlike in case of C, MATLAB array indices start from 1.

f
o
t

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

2
5

3
6

.
B

,
.
A

p
e
D

Addressing an element of the array is done by invoking the

nnumber.
elements row and column
a
r
i
nd row and 3rd
k
i
In order to fetch the
value
of
an
element
in
the
2
v
a
column, we use:
R
y
b
d

e
r
C

>> e = d(2,3)
e
t
a e=
6
K. S. School of Engineering and Management

14

Introduction to MATLAB and Simulink

Addressing multiple elements

M
E
S

S
K
,

E
C
E
commands to address multiple elements in an array.
f
oelements in a row
t
The : (colon) operator is used to address all
p
e
or column.
,. D
The : operator basically tells the
Ainterpreter to address ALL
.
B
elements.
n
a
r
The : operator can also
be used to indicate a range of indices.
i
k
i
v
a
R
y
b
d
e
t
a
e
r
C
Rather than addressing single elements, we can also use

K. S. School of Engineering and Management

15

Introduction to MATLAB and Simulink

M
E
S

S
K
,

Consider the earlier example: d = [1 2 3; 4 5 6]


>> f = d(1, :)

% Address All elements of 1st Row

f=
1
>> g = d(:,2)

p
e
D

% Address All elements in 2nd Column

n
a
ir

g=
2
5

.
B

,
.
A

f
o
t

E
C
E

k
i
v

a
R
>> h = d(1:2,1:2) y %Address Rows from 1 to 2 and Columns from 1 to 2
b
h=
d
e
t1 2
a
e 4 5
r
C
K. S. School of Engineering and Management

16

Introduction to MATLAB and Simulink

M
E
S

Generating Matrices

S
K
,

E
C
E

In some cases, we need to generate large matrices, which is difficult

to generate manually.
There are plenty of built-in commands for this purpose!
of

t
p
e

>> i = 0:10

i=
0

% Generate numbers from 0 to 10 (Integers)

>> j = 0:0.2:1

j=

9 10

n
a
ir

,. D

A
.
B

% Generate numbers from 0 to 1, in steps of 0.2

k
i
v

0 0.2000 0.4000 0.6000 0.8000 1.0000

a
R
>> k = [1:3; 4:6;7:9] % Generate a 3x3 matrix of numbers 1 through 9
y
b
k=
1d 2 3
e
t4 5 6
a
e 7 8 9
r
C
K. S. School of Engineering and Management

17

Introduction to MATLAB and Simulink

M
E
S

Generating Matrices
>> l = ones(3,2)

%Generate a 3x2 matrix populated with 1s

l=
1
1
1

1
1
1

f
o
t

S
K
,

E
C
E

p
e
D

,
.
>> m = zeros(2,4) %Generate a 2x4 matrix ofA
0s
.
m=
B
n
0 0 0 0
a
r
0 0 0 0
i
k
i
v
a
>> n = rand(3,4) %
Generate a 3x4 matrix of random numbers (Between 0 and 1)
R
y
n=
b
0.8147
0.9134 0.2785 0.9649
d
e
0.9058 0.6324 0.5469 0.1576
t
a
e 0.1270 0.0975 0.9575 0.9706
r
C
K. S. School of Engineering and Management

18

Introduction to MATLAB and Simulink

M
E
S

Generating Range of Values

S
K
, a and b
x = linspace(a,b,n)
% Generates n linearly-spaced values between
E
C
(inclusive)
E
f
o
t
>> x = linspace(0,1,7)
p
e
x=
D
, 0.8333 1.0000
.
0 0.1667 0.3333 0.5000 0.6667
A
.
B
n n values between 10 and 10 in logarithm
x = logspace(a,b,n)
% Generates
a
r
space
i
k
i
v
a
R
>> x = logspace(0,1,7)
y
x= b
d
1.0000 1.4678 2.1544 3.1623 4.6416 6.8129 10.0000
e
t
a
e
Cr
a

K. S. School of Engineering and Management

19

Introduction to MATLAB and Simulink

M
E
S

Matrix Operations
Operations upon Matrices can be of two types:
Element-wise Operation
Matrix-wise Operation

f
o
t

,
.
A

S
K
,

E
C
E

p
e
D

Common Arithmetic Operations:


Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Exponentiation (^)
Matrix Inverse (inv)
Left Division (\) [A\B is equivalent to INV(A)*B]
Complex Conjugate Transpose ()

n
a
ir

.
B

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

20

Introduction to MATLAB and Simulink

M
E
S

Matrix Operations

S
K
,

E
C
E

By default, the Operators perform Matrix-wise operations.

f
o
t
dimension mismatch, specially with exponentiation,
division
p
e
and multiplication.
D
,
.
In case of scalar + matrix operations,
A matrix-wise operations are
.
B
equivalent to element-wise operations.
n
a
r
ie.
i
k
i
v = [Scalar + Matrix(i,j)]
Scalar + Matrix
a
R
Scalar
y* Matrix = [Scalar * Matrix(i,j)]
b
d
A doteoperator(.)
preceding the operator indicates Element-wise
t
a
operations.
e
Cr
During Matrix-wise operations, care must be taken to avoid

K. S. School of Engineering and Management

21

Introduction to MATLAB and Simulink

M
E
S

Examples
a = [2 5; 8 1];
% 2 x 2 Matrix
b = [1 2 3; 4 5 6];
% 2 x 3 Matrix
t
c = [1 3; 5 2; 4 6];
% 3 x 2 Matrix
p
e
D
Matrix Addition (or Subtraction): ,
.

S
K
,

Let

>> y = b+c'
y=

5 8
9 12

e
r
C

n
a
ir

k
i
v

a
R
y

Complement:

b
d

d=
e
t
a

A
.
B

% b and c have different dimensions.


2
6

>> d = c'

of

E
C
E

% d is now a 2x3 matrix


1
3

5
2

4
6

K. S. School of Engineering and Management

22

Introduction to MATLAB and Simulink

Multiplication

M
E
S

S
K
,

E
C
>> x = b*c
% b(2x3) * c(3x2) = y (2x2). No dimension mismatch
E
f
o
x=
t
p
23 25
e
53 58
,. D
A the corresponding
In case of element-wise multiplication,
.
B
elements get multiplied (Matrix
Dimensions must agree)
n
a
r
i
k
i
v
>> y = b .* d
% b(2x3)*c(2x3).
No dimension mismatch)
a
R
y=
y
b
1 10 12
d
e
t
12 10 36
a
e
r
C
Matrix Multiplication (Or Division):

K. S. School of Engineering and Management

23

Introduction to MATLAB and Simulink

M
E
S

Exponentiation

S
K
,

E
C
E

Element-wise Exponentiation is NOT the same as Matrix-wide

exponentiation.
f
o
Matrix Exponentiation needs square matrixtas input.
p
>> a^2

% Matrix Exponentiation: ans = a * a


ans =
44 20
32 44

n
a
ir

e
D
.,

A
.
B

k
i
vExponentiation: ans = a .* a
>> a.^2 % Element-wise
a
R
ans =
y
b
4 25
d
e
64 4
t
a
e
r
C
K. S. School of Engineering and Management

24

Introduction to MATLAB and Simulink

M
E
S

Matrix Concatenation

S
K
,

E
C
E

Matrices can be concatenated just like elements in a matrix.

f
o
t

Row-wise concatenation ( separated by space or commas)


>> f = [b d]
f=
1
4

2
5

3
6

1
3

5
2

n
a
ir

4
6

.
B

,
.
A

p
e
D

Column-wise concatenation (separated by semicolon)


>> g = [b ; d]
g=

a
R
y1 2

b
d

e
r
C

e
t
a

k
i
v

4
1
3

5
5
2

3
6
4
6

K. S. School of Engineering and Management

25

Introduction to MATLAB and Simulink

Other useful basic functions

M
E
S

S
K
,
>> randn(n)
% Generates a (n x n) Normally Distributed RandomE
Matrix
C
>> eye(n)
% Generates a (n x n) Identity Matrix
E
f along Row, Column
>> magic(n)
% Generates a (n x n) Magic Matrix (SameoSum
t
and Diagonal)
p
eprimary diagonal of Matrix A
>> diag(A)
% Extracts the elements along the
D
, diagonal matrix, with A, B, C, .. As
.
>> blockdiag(A,B,C,..)
% Generates a block
A
.
diagonal elements.
B
>> length(x)
% Calculates length
of a vector x
n
a
r
>> [m,n] = size(x) % Gives thei[Rows,Columns]
size of vector x
k
i x towards negative infinity (Floor)
>> floor (x)
% Round
v
a
R
>> ceil (x)
% Round x towards positive infinity (Ceiling)
y
>> clc
% Clears Command Window
b
d
>> clear
% Clears the Workspace Variables
e
t
aclose
>>
% Close Figure Windows
e
r
C >>a = []
%Generates an Empty Matrix
K. S. School of Engineering and Management

26

Introduction to MATLAB and Simulink

M
E
S

Common Statistics Functions


Function

Description

f
o
t

Max(x)

Return largest element in a vector (each column)

Min(x)

Return smallest element in a vector (each column)

Mean(x)
Std(x)

,
.
A

S
K
,

E
C
E

p
e
D

Returns mean value of elements in vector (each column)

.
B

Returns standard deviation of elements in vector (each column)

n
a
r
i
Sum(x)
Returns sum of
all
values in vector (each column)
k
i
v of elements in vector (each column)
Prod(x)
Returnsa
product
R
Sort(x)
Sorts
y values in vector in ascending order
b
Corr(x) d Returns Pair-wise correlation coefficient
e
t
a
Plots histogram of vector x
eHist(x)

Median(x)

Returns median of elements in vector (each column)

Cr

K. S. School of Engineering and Management

27

M
E
S

S
K
,

E
C
VISUALIZATIONSoAND
fE
t
p
GRAPHICS ., De
A
.
Graphs, plots and Histograms
B
n
a
r
i
k
i
v
a
R
y
b
d
e
t
a
e
r
C

Introduction to MATLAB and Simulink

M
E
S

MATLAB Graphics

S
K
,

E
C
E

MATLAB provides a wide variety of graphics to visualize data.

f
o
t

Graphics have Interactive tools to manipulate and extract

information from them.


p
e
Graphs can be saved, printed and downloaded
in different image
,. D
formats for use elsewhere.
A
.
MATLAB is capable of: n B

a
r
i
ik

2-D plots (Line, bar, area, Pie, histogram, stem, scatter plots, etc)

v
a
R

3-D plots (Contour, surf, mesh, etc)

y
b
Polar plots (Polar and Compass plots)
d
e
t plots (Feather and Compass plots)
Vector
a
e

Image Processing (Histogram, Image display,etc)

Cr

K. S. School of Engineering and Management

29

Introduction to MATLAB and Simulink

M
E
S

2-D plots
plot(xdata_1, ydata_1, LineSpec_1,..,

S
K
,

E
C
E

xdata_n,ydata_n,LineSpec_n);
f
o
t
xdata Independent variable
p
e
ydata Dependent Variable(s)
D
,
.
A Symbol, color, line style,
LineSpec Line attributes (Marker
.
B
etc)
n

a
r
i
ik

v
a
R

Care must be taken to ensure that xdata and ydata have the same

dimensions
y(no. of columns).
b
d
If ydata
has multiple rows, each rows data will be overlaid on
e
t
agraph.
the
e
r

K. S. School of Engineering and Management

30

Introduction to MATLAB and Simulink

M
E
S

The Figure Window

S
K
,

f
o
t

Edit Plot
Zoom
In/Out

n
a
ir

Pan
Control

.
B

,
.
A

p
e
D

k
i
v

a
R
y

b
d

Rotate

E
C
E

Insert
Legend

Insert
Colorbar

e
t
Data
a
e
CrCursor

K. S. School of Engineering and Management

31

Introduction to MATLAB and Simulink

M
E
S

2-D plot Example


x = 0:0.1:2*pi;
y = sin(x);
z = cos(x);
figure(1);
plot(x, y, 'r--', x, z, 'b-o');
title('Sin(x) vs Cos(x)');
legend('Sin(x)','Cos(x)');
xlabel('Independent Variable (x)');
ylabel('Dependent Variables (y,z)');

n
a
ir

A
.
B

S
K
% Independent Variable : x,
E
% Dependent Variable
1:y
C
E 2:z
% Dependent Variable
f
o No. 1.
% Create Figure
t
% Plot
ypand z wrt x
e
,. %DApply Title to Plot
% Include Legend
% Label X-Axis
% Label Y-Axis

k
i
v
Note: In plot, LineaAttributes
are enclosed in single quotes.
R
r and
b
here specify Line Colors (red and blue
y
b
respectively)
d
e

t -- and -o here indicate the Line Style (Dashed, and


a
e
Dashed with circles respectively)
r
C
K. S. School of Engineering and Management

32

Introduction to MATLAB and Simulink

M
E
S

2-D Plot Example

S
K
,

f
o
t

n
a
ir

.
B

,
.
A

E
C
E

p
e
D

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

33

Introduction to MATLAB and Simulink

Title of the Plot

M
E
S

S
K
,

E
C
E
This command adds the string contents to the Title.
f
o
t
p
>>title(['Hello. The value of \pi = ',num2str(3.14159),' e
approximately']);
,. D
A
.
B
n first converted to string (num2str)
Numerical content has rtoabe
i
k
and then appended as
i a string.
v
a strings, we use the comma operator, and
In order to append
R
y within square brackets (remember, MATLAB sees
enclose them
b
d
everything
as vectors!)
e
t
a
Backslash
Operator (\) is used to include special characters (Eg.
e
r
C \alpha, \beta, etc.)
Syntax: title(String to be displayed);

K. S. School of Engineering and Management

34

Introduction to MATLAB and Simulink

Axes Labels and Legend

M
E
S

S
K
,

E
C
Egraph/line.
to add legends, each corresponding to a separate
f
o
legend(label_1, label_2, , label_n);
t
p
e
xlabel is used to label the X-axis, and ylabel is used to label the YD
,
.
axis.
A
.
B
LATEX conventions can be used
here as well.
n
a
\ for special characters,
^ for superscript and _ for subscript,
r
i
k
i
etc.
v
a
R
y
b
d
e
t
a
e
r
C
In case of multiple graphs in the same window, we use legend

K. S. School of Engineering and Management

35

Introduction to MATLAB and Simulink

M
E
S

Logarithmic Scales

S
K
,

Plot command plots values in linear scale.

f
o
t

E
C
E

In case we need to plot values in logarithmic scale we use:


semilogx(x,y) Where only X-axis is in logarithmic scale

p
e
D

semilogy(x,y) Where only Y-axis is in logarithmic scale

.
B

,
.
A

loglog(x,y) Where both X and Y axes are in logarithmic scale

n
a
ir

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

36

Introduction to MATLAB and Simulink

Multiple Plots in the same graph

M
E
S

S
K
,

E
C
E one graph
use the hold on command to tell MATLAB tofhold
while we plot the other ones on top of it. t o
p
e
>> a = 1:10;
D
,
.
>> b = 1:0.5:10;
% Two different independent
variables in one graph
A
.
>> x = a.^1.5;
B
n
>> y = 10*sin(b);
a
r
i
>> plot(a,x,'r-*');
k
i
v % Hold the graph
>> hold on;
a
>> plot(b,y,'c-o'); R
y
b
>> hold off;
% Once all graphs are plotted, stop adding more graphs
d
e
>> legend('x
% (^ - superscript , _ - subscript)
t = a^1^.^5','y = 10 sin(b)');
a
e
r
C
In case multiple plots need to be added to the same graph, we

K. S. School of Engineering and Management

37

Introduction to MATLAB and Simulink

M
E
S

Multiple plots (using HOLD)


f
o
t

n
a
ir

.
B

,
.
A

S
K
,

E
C
E

p
e
D

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

38

Introduction to MATLAB and Simulink

Multiple plots in the same window

M
E
S

S
K
,

E
C
E

In case we need to use multiple plots in the same figure

window, we use the subplot function.


f
o
t
Syntax: subplot(m, n, index);
p
e
Where : m = No. of rows of plots to,be
in the window
D
.
A to be in the window
n = No. of columns of .plots
B
index = The indexnof the plot to be shown

a
r
i
ik

v
a
Example: To display
a value as the 5th plot in a 2x3 alignment of
R
y
plots, we write:
b
d
>> subplot(2,3,5);
e
at y, r);
>> e
plot(x,
Cr
K. S. School of Engineering and Management

39

Introduction to MATLAB and Simulink

M
E
S

Problem
Given:
T = 0:1e-5:2e-3
% Time base
Fc = 1e4; fm = 2e3
% Signal Frequencies
Vm = 3V; Vc =5V
% Signal Voltages
Wm = 2 fm; Wc = 2 fc
% Angular Frequencies

f
o
t

n
a
ir

.
B

,
.
A

S
K
,

E
C
E

p
e
D

Plot the following signals:


Modulating Signal : vm = Vm sin wmt
Carrier Signal : vc = Vc sin wct

k
i
v

a
R
y

b
d

Plot the AM Wave:


vAM = (Vc+Vm sinwmt)sin wct

e
t
a

e
r
C

K. S. School of Engineering and Management

40

Introduction to MATLAB and Simulink

M
E
S

3-D Plots

S
K
,

MATLAB also supports 3-D plots (x,y,z).


mesh Draw mesh plot (wireframe)
surf Draw shaded mesh plots

.
B

contour Draw contour plots


plot3 3-D Line plot

n
a
ir

,
.
A

f
o
t

E
C
E

p
e
D

k
i
v

a
R
y

plot3 is used whenever Z needs to be plotted as a function of X

and Y. This
is a line plot in 3-dimensions
b
d mesh offer surface plots.
e
Surftand
a
e
rContour plots provide projection in 2-D space.

K. S. School of Engineering and Management

41

Introduction to MATLAB and Simulink

M
E
S

3-D plots : plot3

S
K
,

Example:

f
o
t

x = 0 : pi/50 : 10*pi;
y = sin(x);
z = cos(x);
plot3(x,y,z)
grid on;

n
a
ir

.
B

,
.
A

E
C
E

p
e
D

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

42

Introduction to MATLAB and Simulink

M
E
S

3-D plots : mesh & surf

S
K
,

E
C
E

mesh is used to plot a wireframe plot of a variable z, which is a

function of two variables x and y. [z = f (x,y)] f


t o of x and y.
Surf is used to plot a surface map of z as p
a function
e
General syntax : surf(X, Y, Z)
D
,
.
mesh(X, Y, Z) . A
B
If x is a (1 x m) sized vector,
and y is a (1 x n) sized vector, the
n
a
r
i
z vector has to be of ksize (m x n).
i
v
a z has to have a corresponding value.
For every (x,y) pair,

R
y

b
d

e
t
a

meshgrid function can be used to create a 2-D or 3-D grid with

e given reference vector values.


the
r
C

K. S. School of Engineering and Management

43

Introduction to MATLAB and Simulink

M
E
S

3-D plot : mesh & surf

S
K
,

Example:

f
o
t

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2);
Z = sin(R)./R;
%Sinc function
%Mesh Plot
subplot(2,1,1);
mesh(X,Y,Z);
% Surface Plot
subplot(2,1,2);
surf(X,Y,Z);

n
a
ir

.
B

,
.
A

E
C
E

p
e
D

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

44

Introduction to MATLAB and Simulink

M
E
S

Contour plots

S
K
,

E
C
E

contour function generates a 2-D contour map, from 3-D space.

f
o
t

Contours are color-mapped projection of 3-D surfaces onto 2-D

space.
Example:
[X,Y,Z] = peaks(25);
figure(1);
subplot(2,1,1);
surf(X,Y,Z);
subplot(2,1,2);
contour(X,Y,Z);

n
a
ir

.
B

,
.
A

p
e
D

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

45

Introduction to MATLAB and Simulink

M
E
S

Surface + Contour Plots

S
K
,

In some cases, we need to

visualize data both as


surface/mesh plots, as well as
contour maps.

.
B
meshc and surfc provide Mesh
n
a
and Surface plots respectively,
r
i
k
i
with the corresponding
contour
v
a
plots shown below.
R
y
b
d
e
t
a
e
r
C

f
o
t

,
.
A

E
C
E

p
e
D

K. S. School of Engineering and Management

46

M
E
S

S
K
,

f
o
t

E
C
E

p
e
Operators and Control
,. D
A
.
B
n
a
r
i
k
i
v
a
R
y
b
d
e
t
a
e
r
C

Flow

Introduction to MATLAB and Simulink

M
E
S

Operators

S
K
,

E
C
E

MATLAB allows the use of relational and logical operators

such as:

f
o
t

== Equal To
~= Not Equal To
<

Smaller Than
>
Greater Than
<= Lesser Than or Equal To
>= Greater Than or Equal To
& Logical AND
|
Logical OR

n
a
ir

.
B

,
.
A

p
e
D

k
i
v

a
R
y

b
d

e
t
a

e
r
C

These Operators can be used for control and decision making.


K. S. School of Engineering and Management

48

Introduction to MATLAB and Simulink

M
E
S

Flow Control

S
K
,

E
C
E

Just like in C-language, MATLAB allows for some flow control

statements like:

f
o
t

If-else
For
While
Break

n
a
ir

.
B

,
.
A

p
e
D

k
i
v

a
R
end of the control
statement loop.
y
b
end replaces
the curly brackets used in C/C++
d
e
t
a
re

Whenever control statements are used, end keyword is used to indicate

K. S. School of Engineering and Management

49

Introduction to MATLAB and Simulink

M
E
S

Control Structure : if-else


Syntax:

Example:

if(condition_1)
Commands_1
elseif(condition_2)
Commands_2
elseif(condition_3)
Commands_3
else
Commands_n
end

y
b
d

S
K
,

E
C
E

f
o
If((a>3)t&(b<5))
p
e
x = [1 0];
D
.,

.A

v
a
R

a
r
i
ik

B
n

elseif(((b==5))
x = [1 1];
else
x = [0 1];
end

e
t
a

e
r
C

K. S. School of Engineering and Management

50

Introduction to MATLAB and Simulink

M
E
S

Control Structure: for


Syntax:

Examples:

for i = index_array
Matlab Commands;
end

i
v
a

R
y

b
d

e
t
a

E
C
E

f
o
for i = -1 : t0.01 : 1
p
e
x = i^2+sin(i);
D
,
.
end
.A

B
n

a
r
i
k

S
K
,

or
for k = [0.2 0.4 0.1 0.8 1.3]
y = sin(k);
end

e
r
C

K. S. School of Engineering and Management

51

Introduction to MATLAB and Simulink

M
E
S

Control Structure : while

S
K
,

E
C
E

MATLAB supports the while statement, but not the do-while

statement.

f
o
t

p
e
D
,. Example:

Syntax:
while(condition)
MATLAB Commands;
end

n
a
ir

k
i
v

A
.
B

while((a>4) | (b==5))
z = x + 1;
end

a
R
y

The break statement


is used whenever we need to terminate the
b
d
execution
e
t of a for or while loop.

a
e
r

K. S. School of Engineering and Management

52

Introduction to MATLAB and Simulink

The find function

M
E
S

S
K
,

The find function in MATLAB is very useful for extracting

E
C
index data from matrices, when used with relational
operators.
E
f
o
Example:
t
p
>> x = rand(1,10); % Generates 1x10 matrix of random
values
e
>> y = x > 0.6
% Finds which of the values in, xD
are greater than 0.6
.
y=
A
.
0 0 1 0 0 B
0 1 0 0 0
nof values in x, which are greater than 0.6
>> y = find(x > 0.6) % Returns indices
a
r
i
y=
k
i
3 a7v
R
In order to extract
the values greater than 0.6, we can use:
y
b
>>y = x((x>0.6))
or
y = x(find(x>0.6))
d
e
t y=
a
e
0.7507 0.6101
r
C
K. S. School of Engineering and Management

53

M
E
S

S
K
,

f
o
t

p
e
Scripts and Functions
,. D
A
.
B
n
a
r
i
k
i
v
a
R
y
b
d
e
t
a
e
r
C

E
C
E

Introduction to MATLAB and Simulink

M
E
S

MATLAB Scripts

S
K
,

E
C
E

Scripts are programs written for interpreters (as opposed to

compilers)
f
o
t
Scripts automate execution of tasks for a p
particular
application.
e syntax
MATLAB scripts are based on C-language
D
,
.
% symbol is used for single line. A
comments.
B
MATLAB does not support
multiline
commenting.
n
a
r
i
MATLAB scripts can
be divided into independently-executable
k
i
v%% symbol (Section Breaks). This is very
sections using the
a
R
useful forblarger
y programs with multiple sections.
d
Scripts
e
t are stored with a .m file extension.

a
e
r

K. S. School of Engineering and Management

55

Introduction to MATLAB and Simulink

M
E
S

A Simple Script

S
K
,

f
o
t

n
a
ir

.
B

,
.
A

E
C
E

p
e
D

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

56

Introduction to MATLAB and Simulink

M
E
S

S
K
,

E
C
E
window (default in earlier versions of MATLAB).
f
o are shown in
t
When the script is running, the variable attributes
p
e
the Workspace window.
,. D
Whitespaces are very useful for easy
A reading of code.
.
B
The initial comments serve
as
a quick reference with the help
n
a
r
command.
i
k
i
v
a
R
y
b
d
e
t
a
e
r
C
Script Editor window can be undocked from the command

K. S. School of Engineering and Management

57

Introduction to MATLAB and Simulink

M
E
S

MATLAB Functions

S
K
,

E
C
E

Whenever we have huge programs, with repeated operations, it

is preferable to use functions.


f
o
t
Functions make code more readable and compact.
p
e the code.
Functions speed up processing, and,simplify
D
.
Aby a keyword function, and
MATLAB functions are indicated
.
B
can handle multiple variables.
n
a
ir of three types:
MATLAB Functionskare

i
v
Inline Functions a
R
Anonymous
Functions
y
b
Standalone
Functions
d
e
t
ea

Cr

K. S. School of Engineering and Management

58

Introduction to MATLAB and Simulink

M
E
S

Inline Functions

S
K
,

E
C
E

Inline Functions accept (usually numerical) input and return

output.
f
o
t workspace.
Function evaluation takes place in the current
p
e
Keyword used : inline
D
,
.
A I need to evaluate Cosine
Example : Consider a function .where
B
Law: =
+ n

a
r
i
>> cval = inline('sqrt(a^2+b^2-2*a*b*cos(theta))');
k
i
v
>> d = cval(2, 3, pi/6)
a
d=
R
y 1.6148
b
d
e
Invoke
t function cval anywhere within the program.
a
e functions utilize MATLABs symbolic math capability.
r

Inline
C
K. S. School of Engineering and Management

59

Introduction to MATLAB and Simulink

Anonymous Functions

M
E
S

S
K
,

E
C
E data type
program file, but is associated with a variable whose
f
o
is function_handle.
t
p
e
Can contain only a single executable D
statement.
,
.
Faster than inline functions.
A
.
B
Example : Evaluate Cosine
Law
(as earlier)
n
a
r
i
k
i
>> cval = @(a,b,theta)
v sqrt(a^2+b^2-2*a*b*cos(theta));
a
R
>> d = cval(2,3,pi/6)
y
b
d=
d
e
t
1.6148
a
e
Cr
An anonymous function is a function that is not stored in a

K. S. School of Engineering and Management

60

Introduction to MATLAB and Simulink

M
E
S

Function Files

S
K
,

E
C
E

Commands executed in a separate workspace which is created

whenever the function is called.


f
o
t as the function,
Function files are saved with the same name
p
e
with a .m extension.
D
,
.
During function calls, input and A
output arguments have to be
.
B
specified.
n
a
r
The first (command) line
of a Function M-file MUST be a
i
k
i line specifying input and ouput variables.
function declaration
v
a
R
Make sure that
no undefined variable occurs as input to these
y
b
commands!
d

e
t
a

e
r
C

K. S. School of Engineering and Management

61

Introduction to MATLAB and Simulink

M
E
S

Function File Example

S
K
,

File name : quadroots.m

f
o
t

E
C
E

function [root1,root2] = quadroots(a,b,c)


%quadroots calculates the roots of the quadratic equation given by:
% f(x) = ax^2+bx+c
% Given the coefficients a,b,c as input.
root1 = (-b+sqrt(b.^2-4.*a.*c))/(2.*a);
root2 = (-b-sqrt(b.^2-4.*a.*c))/(2.*a);
end

n
a
ir

.
B

,
.
A

p
e
D

k
i
v

Calling the function quadroots

a
R
>> [r1,r2] = quadroots(3,4,2)
r1 =by
d
-0.6667 + 0.4714i
e
t r2 =
a
e
-0.6667 - 0.4714i

Cr

K. S. School of Engineering and Management

62

Introduction to MATLAB and Simulink

M
E
S

Problem
1.

S
K
,

Create a function that generates the factorial of a given


E
C
number.
fE

o
t
p

e
D
.,

n
a
ir

A
.
B

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

63

M
E
S

Importing and
Data
n
a
ir

k
i
v

a
R
y

b
d

e
r
C

e
t
a

.
B

E
C
Exporting
E
f
o
t
p
e
,. D
A

S
K
,

Introduction to MATLAB and Simulink

M
E
S

Import and Export of Data

S
K
,

E
C
E

MATLAB variables and data can be imported from and

exported to a variety of formats including:


MATLAB formatted data (.mat)
Text (csv, txt, delimited data)
Spreadsheets (xls, xlsx, xlsm, ods)

.
B

Extensible Markup Language (xml)

n
a
ir

,
.
A

f
o
t

p
e
D

Scientific Data (cdf, fits, hdf, h5, nc)

k
i
v

Image (bmp, jpg, png,tiff,gif, pbm, pcf, ico, etc)

a
R
Video (avi,y
mpg, wmv, asf, mp4, mov, etc)
b
d
e
t
a
re

Audio (au, snd, flac, ogg, wav, m4a, mp4, mp3, etc)

K. S. School of Engineering and Management

65

Introduction to MATLAB and Simulink

Import/Export

M
E
S

S
K
,

E
C
E data.
MATLAB commands can be used to import or fexport
o
t
Data import/export can be done in two ways:
p
e
Commands in Command Line
D
,
.
Right Click and Import/Export fromA
Workspace/Command
Window
.
B
n
a
While importing or exporting
data from scripts, we generally
r
i
ik
use the MATLABvcommands.
a
R
Right Click actions are used whenever we are importing data
y
b
from ordexporting data to files, while working in the Command
e
t
window.
a
e
Cr
Depending on the type of files containing the data, different

K. S. School of Engineering and Management

66

Introduction to MATLAB and Simulink

M
E
S

Text Files
csvread
csvwrite
dlmread

S
K
,

Read comma-separated value file


E
C
Write comma-separated value filef E
o
t
Read ASCII-delimited file of
p numeric data into

matrix
,. D
A
dlmwrite
Write matrix to ASCII-delimited
file
.
B
textscan
Read formatted
data from text file or string
n
a
r
i
readtable
Createik
table from file
v
a
writetable Write
table to file
R
type
by Display contents of file

d
e
at

e
r
C

K. S. School of Engineering and Management

67

Introduction to MATLAB and Simulink

Text Import (.txt)

M
E
S

S
K
,

Consider a text file Delhitemp.txt, containing daily average


E
C
temperature data for 20 years (Month-Day-Year-Temp
f E format)

o
t
>> cd('C:\Users\Ravi\Desktop\matlab workshop files\Dataset files');
pdirectory
e
>> fname = 'Delhitemp.txt'; % Name of file in current
D
>> fileID = fopen(fname,'r'); % Open file, (r)ead
,. only
A int, int, int, float
>> fileSpecs = '%d%d%d%f'; %Data format
.
>> C = textscan(fileID,filespecs,'HeaderLines',1);
%Scan text and extract data
B
n
a
r
We See that C is now k
a istructure
with 4 fields:
i
v
C=
a
R
[7125x1 int32] [7125x1 int32] [7125x1 int32] [7125x1 double]
y
b
Now, I can
assign the values to individual fields :
d
e
t
>>TempVals
= C{4} % { } accesses MATLAB cell elements
a
e TempVals is a 7125x1 matrix of floating point values.
r
Now,
C
K. S. School of Engineering and Management

68

Introduction to MATLAB and Simulink

M
E
S

S
K
,

E
C
E

Lets try plotting the temperature variation for the past 20 years!
>>plot(TempVals);
title(['Temperature Variations from ',num2str(C{3}(1,:)), ' to ', num2str(C{3}(end,:))]);
xlabel('Days');
ylabel('Temperature (F)');

f
o
t

Note: C{3}(1,:) accesses the


n
a
first row and all columns r(to
i
k
extract the complete string)
i
v
a 3 (Year)
of Cell Cs fieldRno.
y
Similarly, C{3}(end,:),
b
extractsdthe last year value
e
t
in the
a same field.

.
B

,
.
A

p
e
D

e
r
C

K. S. School of Engineering and Management

69

Introduction to MATLAB and Simulink

M
E
S

Extracting Data

S
K
,

E
C
E

Now, lets try plotting the daily temperatures only for July 2013.

f
o
t

We need to isolate the data pertaining to July in column 1 and

2013 in column 3.
>> Indices = find(C{1}== 7 & C{3}==2013);
>> Plot(C{2}(Indices,:),C{4}(Indices,:));

n
a
ir

.
B

,
.
A

p
e
D

C{2}(Indices,:) grabs the X-axis data


(Days) for the selected range
C{4}(Indices,:) grabs the Y-axis data
(Temperature) for the corresponding
days.
The two lines can be written as:
>> plot(C{2}(find(C{1}== 7 &
C{3}==2013),:),C{4}(find(C{1}== 7 &
C{3}==2013),:)) ;

k
i
v

a
R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

70

Introduction to MATLAB and Simulink

M
E
S

.csv files

S
K
,

E
C
E

Most databases store data in CSV format (Comma Separated

Value), where the comma is the delimiter.


f
o
t CSV data easy.
MATLABs csvread function makes importing
p
ecol);
Syntax: X = csvread(filename.csv, row,
D
,
.
A and column number from
Here, Row and Col indicate the. row
B
which scanning has to commence.
(zero based)
n
a
r
i
In case the CSV fileskhave headers, titles, explanations, etc, we
i
v
can skip those lines
from the files and point the (Row, Col)
a
R
values to the
cell
where the data begins.
y
b
Onceethe
import is done, X becomes a matrix of values where
d
tis stored.
a
data
e

Cr

K. S. School of Engineering and Management

71

Introduction to MATLAB and Simulink

M
E
S

Example

S
K
,

E
C
E

Let us try and extract some BSE data from 1990 to 2014.
Data is in the file bsedata.csv

f
o
Data is in the format: Year Open High t Low Close
p
e
Since the Row 1 is just headers, we will
skip that and load the
D
rest into a variable MarketData. A.,
>> MarketData = csvread('bsedata.csv',1,0);.
B
nin MarketData. Now we can assign
Now, all the data is stored
a
r
i
them to the respective
columns.
k
i
v
YearData = MarketData(:,1);
a
R
OpeningData = MarketData(:,2);
y
HighData =b
MarketData(:,3);
d
LowData
= MarketData(:,4);
e
t
a
ClosingData
= MarketData(:,5);
e
Cr
K. S. School of Engineering and Management

72

Introduction to MATLAB and Simulink

M
E
S

Play around with the data

S
K
,

Now, lets see the market trends..

f
o
t

E
C
E

plot(YearData,OpeningData,'r',YearData,HighData,'m',YearData,LowData,'b',YearData,
ClosingData,'c','LineWidth',2);

Alternatively, since all


columns are of the same size,B.
n
with the same independent
a
r
i
k
variable in column 1,
we can
i
v
write:
Ra

,
.
A

p
e
D

y
b
plot(YearData,
MarketData(:,2:end),
d
e
LineWidth',2);
t
a
e
Cr

K. S. School of Engineering and Management

73

Introduction to MATLAB and Simulink

M
E
S

Writing to csv files

S
K
,

E
C
E

MATLAB variables can be exported into csv format for use

with other applications too.


f
o
t
This is achieved using the csvwrite function:
p
e
Syntax : csvwrite(filename, Variable,DRow, Col)
,
.
A
Example : If I want to write just
the Opening and Closing
.
B
values from my data set, to
a
csv file named
n
BSEOpenClose.csv: ira

k
i
>> csvwrite('BSEopenclose.csv',[YearData
OpeningData ClosingData],1,0);
v
a
R
y
b
The file BSEopenclose.csv is written into the current directory,
d
e
tcontains the year, Closing Data and Opening Data, with
and
a
e being written starting from 2nd row.
r
data
C
K. S. School of Engineering and Management

74

Introduction to MATLAB and Simulink

M
E
S

.xls and .xlsx files

S
K
,

E
C
E

In case data is stored in Excel Spreadsheets, MATLAB can

extract data from that too.


f
o
t extract data from
xlsread is used to read Excel Spreadsheets and
p
e
it.
D
,
.
xlsread can extract data from all A
pages or from a specified set of
.
B
pages.
n
a
xlswrite can be used toirwrite MATLAB workspace variables
k
i
and data into Excel
av Spreadsheets.

R
y

b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

75

Introduction to MATLAB and Simulink

M
E
S

Importing Excel data


E
C
E

Syntax : num = xlsread(filename,sheet,xlRange);

f
o
t

Filename String enclosed in quotes


Sheet Worksheet number

,
.
A

S
K
,

p
e
D

xlRange Range of cell values to be imported

n
a
ir

.
B

Example : tempData = xlsread('IndMinTemp.xls', 'A3:F114');

k
i
v

This reads all values in the spreadsheet from Page 1 (as not

a cells A3 through F114.


specified), andRfrom
y
b
d

e
t
a

e
r
C

K. S. School of Engineering and Management

76

Introduction to MATLAB and Simulink

M
E
S

Exporting to Excel
E
C
E

Syntax : Status = xlswrite(filename,A,sheet,xlRange)

f
o
t

S
K
,

Filename Name of the Excel File to be created.

p
e
D

A Matrix/Vector to be stored in the Spreadsheet

,
.
A

Sheet Sheet Number in the workbook

.
B

xlRange Range of cells in which data is to be stored.

n
a
ir

Status 1 if successful, 0 in case of failure.

k
i
v

a
R
y

Example: To save a variable Num in an excel sheet named

numericalvalue.xlsx:
b

e
r
C

d
e
at

Status = xlswrite(numericalvalue.xlsx, Num)

K. S. School of Engineering and Management

77

Introduction to MATLAB and Simulink

M
E
S

Problem

S
K
,

E
C
E

Get the spreadsheet file : Monthly_And_Annual_Rainfall.xls

f
o
t

Extract data into the workspace.

p
e
D

Plot the annual rainfall values for any 5 cities from 1951 to

2012, clearly indicating the cities. ,


.
A
Plot the seasonal rainfall for the
same 5 cities for the year 1980
.
B
in another graph.
n

a
r
i
ik

y
b
d

v
a
R

e
t
a

e
r
C

K. S. School of Engineering and Management

78

Introduction to MATLAB and Simulink

Acknowledgment

M
E
S

S
K
,

E
C
EMathWorks,
are all trademarks or registered trademarks of The
f
o
Inc.
t
p
e
,. D
A
.
B
n
a
r
i
k
i
v
a
R
y
b
d
e
t
a
e
r
C

MathWorks, MATLAB, Simulink and the Mathworks Logo

K. S. School of Engineering and Management

79

Você também pode gostar