0% found this document useful (0 votes)
15 views

Matlab Report (1)

The document is an industrial training report on the basics of MATLAB, submitted by Arman Chholak for the Bachelor of Technology in Electrical Engineering at Bikaner Technical University. It covers MATLAB's features, environment setup, basic syntax, variables, and common operations, providing a comprehensive overview of its applications in computational mathematics and engineering. The report includes acknowledgments and a certificate of originality under the supervision of Dr. Prem Pal Singh.

Uploaded by

jaxaw63941
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Matlab Report (1)

The document is an industrial training report on the basics of MATLAB, submitted by Arman Chholak for the Bachelor of Technology in Electrical Engineering at Bikaner Technical University. It covers MATLAB's features, environment setup, basic syntax, variables, and common operations, providing a comprehensive overview of its applications in computational mathematics and engineering. The report includes acknowledgments and a certificate of originality under the supervision of Dr. Prem Pal Singh.

Uploaded by

jaxaw63941
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Basics of MATLAB

INDUSTRIAL TRAINING REPORT

Submitted in partial fulfillment of the requirements for the

Award of the degree of

BACHELOR OF TECHNOLOGY
In

ELECTRICAL ENGINEERING

Under the Supervision of


Submitted By
Dr. Prem Pal Singh
ARMAN CHHOLAK (23EMCEE006)

BIKANER TECHNICAL UNIVERSITY, BIKANER

MtTRC
MODERN INSTITUTE OF TECHNOLOGY & RESEARCH CENTRE
ALWAR
NOVEMBER, 2024
(2024-25)
BIKANER TECHNICAL UNIVERSITY, BIKANER

CERTIFICATE

Certified that this “Basics of MATLAB” Industrial Training report is the

original work of “ARMAN CHHOLAK” student of B. Tech. II Year III

Semester (Electrical Engineering) who carried out the Industrial Training

work under my supervision.

SIGNATURE SIGNATURE

Mr. Prashant Tyagi Dr. Prem Pal Singh

HEAD OF THE DEPARTMENT SUPERVISOR

Department of EE Department of EE

i
ACKNOWLEDGEMENT

Firstly, we would like to express our gratitude to our advisor for the beneficial comments
and remarks.
We express our sincere thanks to Professor, Dr. S. K. Sharma (Director)of the Modern
Institute of Technology & Research Centre, Alwar.

We pay our deep sense of gratitude to Professor, Prashant Tyagi, Head of the
Department, Electrical Engineering of Modern Institute of Technology & Research Centre,
Alwar for encouraging us to the highest peak and providing us the opportunity to present
the Project.

We acknowledge a deep sense of gratitude to Dr. Prem Pal Singh, Supervisor, Department
of Electrical Engineering, Modern Institute of Technology & Research Centre, Alwar
(Rajasthan) for her constant support and guidance during this work. His honesty,
thoroughness, and perseverance have been a constant source of inspiration for us.

We would like to thank our institute and faculty members without them this project would
have been a distant reality, we also extend our heartfelt thanks to our families and well-
wishers.

Finally, but not least, our parents are also an important inspiration for us. With due respect,
we express our gratitude to them.

ARMAN CHHOLAK (23EMCEE006)

ii
TABLE OF CONTENTS

ACKNOWLEDGEMENT………………………………………………………................ii
TABLE OF CONTENTS………………………………………………………………iii

DAY 1: OVERVIEW………………………………………………………… ……….5


DAY 2: ENVIRONMENT……………………………………………………………….7

DAY 3: BASIC SYNTAX……………………………………………………………….10


DAY 4: VARIABLES……………………………………………………………….16
DAY 5: OPERATORS………………………………………………………………. 25
DAY 6: PLOTTING………………………………………………………………. 31
DAY 7: SIMULINK………………………………………………………………. 38
1.OVERVIEW
OV

MATLAB (matrix laboratory) is a fourth-generation high-level programming language and


interactive environment for numerical computation, visualization and programming.

MATLAB is developed by MathWorks.


It allows matrix manipulations; plotting of functions and data; implementation of algorithms;
creation of user interfaces; interfacing with programs written in other languages, including C,
C++, Java, and FORTRAN; analyze data; develop algorithms; and create models and
applications.
It has numerous built-in commands and math functions that help you in mathematical
calculations, generating plots, and performing numerical methods.

MATLAB's Power of Computational Mathematics


MATLAB is used in every facet of computational mathematics. Following are
some commonly used mathematical calculations where it is used most
commonly:

• Dealing with Matrices and Arrays


• 2-D and 3-D Plotting and graphics
• Linear Algebra
• Algebraic Equations
• Non-linear Functions
• Statistics
• Data Analysis
• Calculus and Differential Equations
• Numerical Calculations
• Integration
• Transforms
• Curve Fitting
• Various other special functions

FeaturesofMATLAB
5
Following are the basic features of MATLAB:
• It is a high-level language for numerical computation, visualization
and application development.
• It also provides an interactive environment for iterative exploration,


2. ENVIRONMENT
designand problem solving.
It provides vast library of mathematical functions for linear algebra,
statistics, Fourier analysis, filtering, optimization, numerical
integration andsolving ordinary differential equations.
• It provides built-in graphics for visualizing data and tools for creating
custom plots.
• MATLAB's programming interface gives development tools for
improving code quality, maintainability, and maximizing performance.
• It provides tools for building applications with custom graphical interfaces.
• It provides functions for integrating MATLAB based algorithms with
external applications and languages such as C, Java, .NET and
Microsoft Excel.

Uses of MATLAB
MATLAB is widely used as a computational tool in science and
engineering encompassing the fields of physics, chemistry, math
and all engineering streams. It is used in a range of applications
including:
• signal processing and Communications
• image and video Processing
• control systems
• test and measurement
• computational finance

6
2.Environment
LocalEnvironmentSetup
Setting up MATLAB environment is a matter of few clicks. The installer can be
downloaded from http://in.mathworks.com/downloads/web_downloads:

MathWorks provides the licensed product, a trial version and a student


version as well. You need to log into the site and wait a little for their
approval.
After downloading the installer, the software can be installed through few clicks.

lnrul MathWo,la Softwort

This progrtm wlll •nNII Mtthl'/O<b products on you, computtr. Vov m,y •bo be rcqu,rcd to
MATLAB'
~yoursoftw.re.
Slt\lfULINK.
O lnlhD U$1J>Q t/lt lnttmei R2013o
lnlhU wrthou1 using I/It lnttrntt

MtthWorlcs p<odU<U •rt p<ot«tcd by potents~ www.mathworlcs.com/pottnls) •nd copynghl


i.ws. By tnttring into I/It Softw•rt lrctnst Ag,_t I/lot follows, you win olso •grtt to
oddibontl rtstricbOns on your use of these p,ogr•ms. Any unouthori:cd u-~ r<9<odUCbol\ o,
disuibution m,y resu~ w, <Ml •nd aim1n1I pen,itie.

MAllA8 •nd Swnu6nk ••t reglSltrcd tnclttNrlcs of The MothWO<lc$. In<. Plust stt
www.molhwo<b.com/boc!emor1cs fo, a list of •clcf<tJoNI ttoc!emor1cs. Othu p<oduct or bf•nd
n,mes m,y be tt..Stf'nlrlcs o, reg!Sltrcd ttoc!emorlcs of t/lor rtspt<IN'< holdtn.

•) Marh\\brks

7
4t. 1%~t• Cl El

lnsl.it,ng MATLAB SJ About 40 m,nutts rt<Nuung

1-

•) Math\\orks·

UnderstandingtheMATLABEnvironment
MATLAB development IDE can be launched from the icon created on the
desktop. The main working window in MATLAB is called the desktop. When
MATLAB is started, the desktop appears in its default layout:

~, I

nut

~----------------------~-·
The desktop has the following panels:
Current Folder - This panel allows you to access the project folders and
files.
8
Command Window - This is the main area where commands can be
entered at the command line. It is indicated by the command prompt
(>>).
Workspace - The workspace shows all the variables created and/or
imported from files.
Command History - This panel shows or rerun commands that are
entered at the command line.

9
3.Basic Syntax
MATLAB environment behaves like a super-complex calculator. You can
enter commands at the >> command prompt.
MATLAB is an interpreted environment. In other words, you give a command
and MATLAB executes it right away.

HandsonPractice
Type a valid expression, for example,

5 + 5

And press ENTER

When you click the Execute button, or type CTRL+E, MATLAB executes
it immediately and the result returned is:

Ans = 10

Let us take up few more examples:

3 ^ 2 % 3 raised to the power of 2

When you click the Execute button, or type CTRL+E, MATLAB executes
it immediately and the result returned is:

Ans = 9

Another example,

sin (pi /2) % sine of angle 90o

When you click the Execute button, or type CTRL+E, MATLAB executes
it immediately and the result returned is:
10
Ans = 1

Another example,

7/0 % Divide by zero

When you click the Execute button, or type CTRL+E, MATLAB executes
it immediately and the result returned is:

Ans = Inf

warning: division by zero

Another example,

732 * 20.3

When you click the Execute button, or type CTRL+E, MATLAB executes
it immediately and the result returned is:

Ans = 1.4860e+04

MATLAB provides some special expressions for some mathematical


symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for 'not
a number'.

UseofSemicolon(;)inMATLAB
Semicolon (;) indicates end of statement. However, if you want to
suppress and hide the MATLAB output for an expression, add a semicolon
after the expression.
For example,

x = 3;

y = x + 5

11
When you click the Execute button, or type CTRL+E, MATLAB
executes it immediately and the result returned is:

y = 8

Adding Comments
The percent symbol (%) is used for indicating a comment line. For example,
x = 9 % assign the value 9 to x

You can also write a block of comments using the block comment
operators % { and % }.
The MATLAB editor includes tools and context menu items to
help you add, remove, or change the format of comments.
CommonlyusedOperatorsandSpecialCharacters
MATLAB supports the following commonly used operators and special
characters:

Operator Purpose

+ Plus; addition operator.

- Minus; subtraction operator.

* Scalar and matrix multiplication operator.

.* Array multiplication operator.

^ Scalar and matrix exponentiation operator.

.^ Array exponentiation operator.

\ Left-division operator.

/ Right-division operator.

12
.\ Array left-division operator.

./ Array right-division operator.

: Colon; generates regularly spaced elements and represents


an entire row or column.

() Parentheses; encloses function arguments


and array indices; overrides precedence.

[] Brackets; enclosures array elements.

. Decimal point.

… Ellipsis; line-continuation operator

, Comma; separates statements and elements in a row

; Semicolon; separates columns and suppresses display.

% Percent sign; designates a comment and


specifies formatting.

_ Quote sign and transpose operator.

._ Non-conjugated transpose operator.

= Assignment operator.

13
SpecialVariablesandConstants
MATLAB supports the following special variables and constants:

Name Meaning

ans Most recent answer.

eps Accuracy of floating-point precision.

i,j The imaginary unit √-1.

Inf Infinity.

14
NamingVariables
Variable names consist of a letter followed by any number of letters,
digits or underscore.
MATLAB is case-sensitive.

Variable names can be of any length, however, MATLAB uses only


first N characters, where N is given by the function namelengthmax.

SavingYourWork
The save command is used for saving all the variables in the
workspace, as a file with .mat extension, in the current
directory.
For example,

save myfile

You can reload the file anytime later using the load command.

load myfile

15
4.Variables
In MATLAB environment, every variable is an array or

matrix. You can assign variables in a simple way. For

x = 3 % defining x and initializing it with a value

example,

MATLAB will execute the above statement and return the following result:

x =3

It creates a 1-by-1 matrix named x and stores the value 3 in its element.
Let us check another example,

x = sqrt(16) % defining x and initializing it with an expression

MATLAB will execute the above statement and return the following result:

x = 4

Please note that:


Once a variable is entered into the system, you can refer to it
later. Variables must have values before they are used.
When an expression returns a result that is not assigned to any
variable, the system assigns it to a variable named Ans, which can be
used later.
For example,

sqrt(78)

MATLAB will execute the above statement and return the following result:

Ans = 8.318

16
You can use this variable Ans:

9876/Ans

MATLAB will execute the above statement and return the following result:
Let's look at another example:
Ans = 1.1182e+03

x = 7 * 8;

y = x * 7.89

MATLAB will execute the above statement and return the following result:

y = 441.8400

Multiple Assignments
You can have multiple assignments on the same line. For example,

a = 2; b = 7; c = a * b;

MATLAB will execute the above statement and return the following result:

c = 14

I have forgotten the Variables!


The who command displays all the variable names you have used.
17
who

MATLAB will execute the above statement and return the following result:

Your variables are: Ans b c x y

The whos command displays little more about the variables:


Variables currently in memory Type of each variables
Memory allocated to each variable Whether they are complex variables or
not

whos

MATLAB will execute the above statement and return the following result:

The clear command deletes all (or the specified) variable(s) from the
memory.

clear x % It will delete x, won't display anything

clear % It will delete all variables in the workspace

% Peacefully and unobtrusively

Long Assignments
Long assignments can be extended to another line by using an ellipsis (...).
For example,

initial velocity = 0;

acceleration = 9.8;

time = 20;

final velocity = initial velocity ...

+ acceleration * time 18
MATLAB will execute the above statement and return the following result:

final velocity =

196

The format Command


By default, MATLAB displays numbers with four decimal place values. This is
known as short format.
However, if you want more precision, you need to use the format
command. The format long command displays 16 digits after decimal.
For example:
format long

x = 7 + 10/3 + 5 ^ 1.2

MATLAB will execute the above statement and return the following result:
x =17.231981640639408

17.231981640639408

Another example,

format short

x = 7 + 10/3 + 5 ^ 1.2

19
MATLAB will execute the above statement and return the following result:
x = 17.2320

The format bank command rounds numbers to two decimal places. For
example,

format bank

daily_wage = 177.45;

weekly_wage = daily_wage * 6

MATLAB will execute the above statement and return the following result:

weekly_wage =

1064.70

MATLAB displays large numbers using exponential notation.


The format short e command allows displaying in exponential form with four
decimal places plus the exponent.
For example,

format short e

4.678 * 4.9

20
MATLAB will execute the above statement and return the following result:

ans =

2.2922e+01

The format long e command allows displaying in exponential form with four
decimal places plus the exponent. For example,

format long e x = pi

MATLAB will execute the above statement and return the following result:

x =3.141592653589793e+00

The format rat command gives the closest rational expression resulting from a
calculation. For example,
format rat

4.678 * 4.9

21
MATLAB will execute the above statement and return the following result:

Ans = 2063/90

2063/90

Creating Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating two
types of vectors:
Row vectors Column vectors
Row vectors are created by enclosing the set of elements in square
brackets, using space or comma to delimit the elements.
For example,

r = [7 8 9 10 11]

MATLAB will execute the above statement and return the following result:

r =

7 8 9 10

Column
5

22
Another example,

r = [7 8 9 10 11];

t = [2, 3, 4, 5, 6];

res = r + t

MATLAB will execute the above statement and return the following result:

res =

9 11 13 15

Column
5

Column vectors are created by enclosing the set of elements in square brackets,
using semicolon (;) to delimit the elements.

c = [7; 8; 9; 10; 11]

MATLAB will execute the above statement and return the following result:

c =

10

11

23
Creating Matrices
A matrix is a two-dimensional array of numbers.
In MATLAB, a matrix is created by entering each row as a sequence of
space or comma separated elements, and end of a row is demarcated by

m = [1 2 3; 4 5 6; 7 8 9}

a semicolon. For example, let us create a 3-by-3 matrix as:

MATLAB will execute the above statement and return the following result:
m=1 2 3
4 5 6
7 8 9

24
5.Operators

An operator is a symbol that tells the compiler to perform specific


mathematical or logical manipulations. MATLAB is designed to operate
primarily on whole matrices and arrays. Therefore, operators in MATLAB
work both on scalar and non- scalar data. MATLAB allows the following
types of elementary operations:
Arithmetic Operators Relational Operators Logical Operators Bitwise
Operations Set Operations

Arithmetic Operators
MATLAB allows two different types of arithmetic operations: Matrix
arithmetic operations
Array arithmetic operations

Matrix arithmetic operations are same as defined in linear algebra.


Array operations are executed element by element, both on one-
dimensional and multidimensional array.

The matrix operators and array operators are differentiated by the


period (.) symbol. However, as the addition and subtraction operation is
same for matrices and arrays, the operator is same for both cases. The
following table gives brief description of the operators:

Ope Description
rat
or
+ Addition or unary plus. A+B adds the values
stored in variables A and B. A and B must
have the same size, unless one is a scalar.
A scalar can be added to a matrix of any
size.

25
- Subtraction or unary minus. A-B subtracts
the value of B from A. A and B must have the
same size, unless one is a scalar. A scalar
can be subtracted from a matrix of any size.

* Matrix multiplication. C = A*B is the linear


algebraic product of the matrices A and B.
More precisely,

..,
C(i,J) • I,ACi,k)Bll<,11

For non-scalar A and B, the number of


columns of A must be equal to the number of
rows of B. A scalar can multiply a matrix of
any size.
.* Array multiplication. A.*B is the element-
by-element product of the arrays A and B. A
and B must have the same size, unless one of
them is a scalar.
/ Slash or matrix right division. B/A is
roughly the same as B*inv(A). More
precisely, B/A = (A'\B')'.
./ Array right division. A./B is the matrix
with elements A(i,j)/B(i,j). A and B must
have the same size, unless one of them is a
scalar.
\ Backslash or matrix left division. If A is a
square matrix, A\B is roughly the same as
inv(A)*B, except it is computed in a
different way. If A is an n-by-n matrix and
B is a column vector with n components, or a
matrix with several such columns, then X =
A\B is the solution to the equation AX = B.
A warning message is displayed if A is badly
scaled or nearly singular.
.\ Array left division. A.\B is the matrix with
elements B(i,j)/A(i,j). A and B must have
the same size, unless one of them is a
scalar.
26
^ Matrix power. X^p is X to the power p, if p
is a scalar. If p is an integer, the power
is computed by repeated squaring. If the
integer is negative, X is inverted first.
For other values of p, the calculation
involves eigenvalues and eigenvectors, such
that if [V,D] = eig(X), then X^p = V*D.^p/V.
.^ Array power. A.^B is the matrix with
elements A(i,j) to the B(i,j) power. A and B
must have the same size, unless one of them
is a scalar.

' Matrix transpose. A' is the linear algebraic


transpose of A. For complex matrices, this
is the complex conjugate transpose.
.' Array transpose. A.' is the array transpose
of A. For complex matrices, this does not
involve conjugation.

Example
The following examples show the use of arithmetic operators on scalar
data. Create a script file with the following code:

27
a = 10;

b = 20;

c = a + b

d = a - b

e = a * b

f = a / b

g = a \ b

x = 7;

y = 3;

z = x ^ y

When you run the file, it produces the following result:

c =

d =

-10

e =

20

0
f = 0.5000
g =
f =

2
0.5000
z =

34

3
Functions for Arithmetic Operations
Apart from the above-mentioned arithmetic operators, MATLAB provides the
28
following commands/functions used for similar purpose:

Function Description

uplus(a) Unary plus; increments by the


amount a
plus (a,b) Plus; returns a + b

uminus(a) Unary minus; decrements by the


amount a
minus(a, b) Minus; returns a - b

times(a, b) Array multiply; returns a.*b

mtimes(a, b) Matrix multiplication; returns a*


b
rdivide(a, b) Right array division; returns a ./
b
ldivide(a, b) Left array division; returns a.\ b

mrdivide(A, Solve systems of linear equations


B) xA = B for x
mldivide(A, Solve systems of linear equations
B) Ax = B for x
power(a, b) Array power; returns a.^b

mpower(a, b) Matrix power; returns a ^ b

cumprod(A) Cumulative product; returns an


array of the same size as the
array A containing the cumulative
product.
If A is a vector, then cumprod(A)
returns a vector containing the
cumulative product of the elements
of A.
If A is a matrix, then cumprod(A)
returns a matrix containing the
cumulative products for each
29
column of A.
If A is a multidimensional array,
then cumprod(A) acts along the
first non-singleton dimension.
cumprod(A, Returns the cumulative product
dim) along dimension dim.
cumsum(A) Cumulative sum; returns an array A
containing the cumulative sum.
If A is a vector, then cumsum(A)
returns a vector containing the
cumulative sum of the elements of
A.
If A is a matrix, then cumsum(A)
returns a matrix containing the
cumulative sums for each column of
A.
If A is a multidimensional array,
then cumsum(A) acts along the
first non-singleton dimension.
cumsum(A, Returns the cumulative sum of the
dim) elements along dimension dim.
diff(X) Differences and approximate
derivatives; calculates
differences between adjacent
elements of X.
If X is a vector, then diff(X)
returns a vector, one element
shorter than X, of differences
between adjacent elements: [X(2)-
X(1) X(3)-X(2) ... X(n)- X(n-1)]
If X is a matrix, then diff(X)
returns a matrix of row
differences: [X(2:m,:)-X(1:m-1,:)]
diff(X,n) Applies diff recursively n times,
resulting in the nth difference.

30
6.Plotting
To plot the graph of a function, you need to take the following step:

Define x, by specifying the range of values for the variable x, for


which the function is to be plotted
Define the function, y = f(x)
Call the plot command, as plot(x, y)
Following example would demonstrate the concept. Let us plot the simple
function y = x for the range of values for x from 0 to 100, with an
increment of 5.
Create a script file and type the following code:

x = [0:5:100];

y = x;

plot(x, y)

When you run the file, MATLAB displays the following plot:
100--------------------
~

ro
~

10

31
Let us take one more example to plot the function y = x2. In this
example, we will draw two graphs with the same function, but in second
time, we will reduce the value of increment. Please note that as we
decrease the increment, the graph becomes smoother.

Create a script file and type the following code:

x = [1 2 3 4 5 6 7 8 9 10];

x = [-100:20:100];

y = x.^2;

plot(x, y)

When you run the file, MATLAB displays the following plot:

10000~~-~-~-~-~-~-~-~--~

9000

8000

7000

6000

5000

4000

3000

2000
1000

~ -60 -40 -20 0 20 40 60 80 100

Change the code file a little, reduce the increment to 5:

32
x = [-100:5:100];

y = x.^2;

plot(x, y)

MATLAB draws a smoother graph:


10000

9000

8000

7000

6000

5000

4000

3000

2000

1000

-~00 -80 -60 -40 -20 0 20 40 60 80 100

Adding Title, Labels, Grid Lines, and Scaling on the


Graph
MATLAB allows you to add title, labels along the x-axis and y-axis, grid
lines and also to adjust the axes to spruce up the graph.
The xlabel and ylabel commands generate labels along x-axis and y-axis.
The title command allows you to put a title on the graph.
The grid on command allows you to put the grid lines on the graph.
The axis equal command allows generating the plot with the same scale
factors and the spaces on both axes.
The axis square command generates a square plot.
Example
33
Create a script file and type the following code:

x = [0:0.01:10];

y = sin(x);

plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),

grid on, axis equal

MATLAB generates the following graph:


Sin(x) G,aph

3 ...........•...... .
. ..........................
' .

2 ...........•...... .............
'••···· ...... ....... ······~···
'
'
'
'

icii 0
' .
·1
:::::::::::::::::::~..... ::···r···· .• _····r··-r···r .••
. .. ..
. .. ..
···················-····· .' .' '' .. .. .
..........................................
·2
'
''' ''' .. ....
... ... ...
'
.
'
' '
' '
'
..
.
.3
.. ..
• • • • • : • • • • • • ~-- · - - · ~ · - · · ·
' '
...
'
.. ...
•••••• : ······~····· ·-:·-··· ··!"···. --~---··

0 2 3 s 6 8 10
,c

Drawing Multiple Functions on the Same Graph


You can draw multiple graphs on the same plot. The following example
demonstrates the concept:

Example
Create a script file and type the following code:

34
x = [0 : 0.01: 10];

y = sin(x);

g = cos(x);

plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')

MATLAB generates the following graph:

08

06

04

02

-0 2

-0 J

-0 6

-0 8

2 3 J 5 6 7 8 9 10

Setting Colors on Graph


MATLAB provides eight basic color options for drawing graphs. The
following table shows the colors and their codes:

Code Color

w White

k Black

35
b Blue

r Red

c Cyan

g Green

m Magenta

y Yellow

Example
Let us draw the graph of two polynomials
f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and g(x) = 5x3 + 9x + 2
Create a script file and type the following code:

x = [-10 : 0.01: 10];

y = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;

g = 5 * x.^3 + 9 * x + 2;

plot(x, y, 'r', x, g, 'g')

When you run the file, MATLAB generates the following graph:

36
OS

-0 s
-1
-10 -8 -4 -2 0 2 4 6 8 10

37
7.Simulink
Simulink is a simulation and model-based design environment for dynamic
and embedded systems, integrated with MATLAB. Simulink, also developed by
MathWorks, is a data flow graphical programming language tool for
modeling, simulating and analyzing multi-domain dynamic systems. It is
basically a graphical block diagramming tool with customizable set of
block libraries.
It allows you to incorporate MATLAB algorithms into models as well as
export the simulation results into MATLAB for further analysis.
Simulink supports:
• system-level design

• simulation
• automatic code generation
• testing and verification of embedded systems
UsingSimulink
To open Simulink, type in the MATLAB work space:

Simulink

Simulink opens with the Library Browser. The Library Browser is used for
building simulation models.

38
~ Simulink Library Browser
fol• fdit '[t~v Help
» Enter search term

Libraries U>rary: Sirofnk Search ResulS: (none) Frequenll'fU-


~ Simulink
~
Commonlyl./Md
Commonly Used Blocks
Slo<b
Continuous
Discontinuities
Discrete
Logic and Bit Operations ~ Continuou.,

Lookup Tables
Math Operations
Model Verification ~ Oi1,c:ontinuitiff

Model-Wide Utilities
Ports & Subsystems
Signal Attributes i:
~ Oi><n:•

~
Signal Routing Logie and Sit
Sinks ~ Opemforu
Sources

,
Us"·Defined Functions
• Additional Math & Oiscr,
._ Aerospace Blockset
El L-pTabl.,

1
~
Communications Systen M•tll
Computer Vision Syste 1
X Opti•tloru

Conuol System Toolbox


DSP System Toolbox
Embedded Coder
[§] Moc!tl
VtflfiOltion

Fuzzy Logic Toolbox


HDL Verifier E] Moc!tl•Wldt
Utihtitt
Image Acquisition Toolb
Instrument Control Toolf
Model Predictive Contro
Neural Network Toolbox
~a Pon,&
Subsy>ltm>

OPCToolbox
Real• Time Windows Tari
[§ Slgn1t Altnbut..

~
Report Generator
Sign1t Routing
Robust Control Toolbox ~
111

Showing: Smuink

On the left side window pane, you will find several libraries categorized on the
basis of various systems, clicking on each one will display the design blocks on the
right window pane.
Building Models
To create a new model, click the New button on the Library Browser's toolbar. This opens a
new untitled model window

39
--- - ----~- - ,.. ... .. -
Iii< t• ii.- ~
,......~

--~-
.z • II
-
li5@ • Iii

•.:i.-
,a
0
!J • ~-J ~-iii,·

=s
B

·- •
- -
A Simulink model is a block diagram.
Model elements are added by selecting the appropriate elements from the Library Browser and
dragging them into the Model window.
Alternately, you can copy the model elements and paste them into the model window.

Examples
Drag and drop items from the Simulink library to make your project.

For the purpose of this example, two blocks will be used for the simulation - A Source (a
signal) and a Sink (a scope). A signal generator (the source) generates an analog signal,
which will then be graphically visualized by the scope(the sink).

40
..A>nlrleS LC>tory ,,,11n s..,c1111Muls (none) Fr enllyU-S,
• .....
~ ~
Commonly Used Blocks Commonl)'I.Md
Con~
Continuous
e-.
Discontinuities
Oisc,ete
L09i< and B~ OpmtioM ~ Chtoc)(lt,n,.ut,t:t
~ auc,;o

Lookup Tobles ,._,


~14th OpcrttloM
Modtl Vttificotion
Modtl•Widt Utilities
~ - loQloand8,1
Opwotiom El Tablff

§ ~
Math M
Pl>rts & Subsystems It ep.,.~, \Wlfl
Signal Attributes """
• n~IRouttn
Sinks
Sources
EJ Mod4if.Yt1ff
UbhlM'.'I G Pon,
S.bt' ,.,...

~ I@
su• e 1n unctions Slgn.ol....,,l""t" Sig RO<rtlng
P Additional Math & Discrttt E

~'-
>; Atr0>paet Blockset
Communications Systm1 Toolbox
Computtr Vision Syrttm Toolbox
Control Systtm Toolbo•
Som
ffil
' OSP Systtm Toolbox
Embtddtd Coder
B UW-0.finff
Funaions [El ,.
Fuz.;, Logic Toolbo•
.,_ uni u • .:r~-

Begin by dragging the required blocks from the library to the project window. Then, connect
the blocks together which can be done by dragging connectors from connection points on one
block to those of another.
Let us drag a 'Sine Wave' block into the model.

41
Logic and Bit Operations
Lookup Tables
at perations
71 Counta Free--
Running
Model Verification
Model-Wide Utilities
Digital Clodc
Ports & Subsystems
Signal Attribute.s
Signal Routing
From File
Sinks
Sources
User-Defined Functions
t Additional Math & Discrete
- Ground

!> t>a. Aerospace Blockset


!> t>a. Communications System Toolbox Pulse Generator
!> t>a. Computer Vision System Toolbox
t>a. Control System Toolbox Random
!> t>a. DSP System Toolbox Number
!> t>a. Embedded Coder
!> t>a. Fuzzy Logic Toolbox Repealing Se-
!> t>a. HDL Verifier quence lnterp...
t>a. Image Acquisition Toolbox
t>a. Instrument Control Toolbox Signal Builda
t>a. Model Predictive Control Toolbox
!> t>a. Neural Network Toolbox
t>a. OPC Toolbox Sine Wave

t>a. Real-Time Windows Target


t>a. Report Generator Uniform Rsn-
t>a. Robust Control Toolbox dom Number
!> t>a. SimEvents

Select 'Sinks' from the library and drag a 'Scope' block into the model.
uwaries Library: SITllint/Snks Searcll Resuls: (none) freq ◄

• Simulink
Commonly Used Blocks
Continuous
i I Ohplay
B FlooilngSco«>e

Discontinurties
Discrete
Logic and Bit Op~ations
>o=) Outt
le So,pe

lookup Tables
Math Operations
Model Verification
e Step s,mulation
@] Termi.natct

Model-Wide Utilities
Ports & Subsystems
Signal Attributes
i~•*rwi To FIie
~ ToW~

~
~nal Routinl )(;<(G<•pl,
I e
Sources
User-Defined Functions
"

Drag a signal line from the output of the Sine Wave block to the input of the Scope block.

42
file sdit )liew Qisplay Diagram ~imulation 8nalysis ~ode Jools ]:felp

(_!) • 10.0

Model Browser •§ untitled


t>a untitled ® ~untitled

[@.)
~ . ffi
Sine Wave
BScope
::::;

Model Browser •§ untitled


t>a untitled ® ~untitled

;~
[]]
::::;
ru ·B
Sine Wave Scope

Run the simulation by pressing the 'Run' button, keeping all parameters default (you can
change them from the Simulation menu)
You should get the below graph from the scope.

43
,=.,0 WJ• • Ill
r,

/
o.5 I
o'
/

44

You might also like