0% found this document useful (0 votes)
9 views138 pages

2 - Introduction To MATLAB and Simulink

The document provides an introduction to MATLAB and its functionalities, highlighting its high-level programming capabilities and ease of use compared to low-level languages. It covers key concepts such as scripts, variables, matrix operations, and basic plotting functions. Additionally, it explains the importance of algorithms in problem-solving and the structure of MATLAB code.

Uploaded by

amrsdiik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views138 pages

2 - Introduction To MATLAB and Simulink

The document provides an introduction to MATLAB and its functionalities, highlighting its high-level programming capabilities and ease of use compared to low-level languages. It covers key concepts such as scripts, variables, matrix operations, and basic plotting functions. Additionally, it explains the importance of algorithms in problem-solving and the structure of MATLAB code.

Uploaded by

amrsdiik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 138

Fundamentals of Mechatronics Engineering

Introduction to MATLAB and


Simulink
Dr. Ahmed Asker
What is Matlab?

 Matlab is basically a high-level language which has many


specialized toolboxes for making things easier for us
 How high?

MATLAB

High Level
Languages such as
C, Pascal etc

Assembly

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 2


Program vs. Script

 Computers only understand low-level language machine code


◦ Low-level languages are much faster, but very difficult for humans to write
efficiently
 MATLAB is a high-level language
◦ Uses code that is human readable
◦ Much easier to write
◦ E.g. “disp”, “fprintf”, “plot”, etc…
 Compiler: Translates a high-level language into an executable
object code program (*.exe in MS Windows)
◦ Creates an executable file (binary) from source code (ascii)
E.g. Microsoft Office (source code: C++)
winword.exe (machine language executable files)
◦ MATLAB does something a little different…

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 3


Program vs. Script

 MATLAB is an interpreted language


◦ Code is read line by line by an interpreter (not a compiler)
◦ Each line of code is translated into machine language and executed
on the fly
◦ No .exe file is generated (can use MATLAB compiler to make .exe
files)
 Because MATLAB code is not compiled…
◦ source code is referred to as a script
◦ Also called M-files (end in .m)
 Advantages
◦ Don’t need to spend time compiling the code to use it
◦ Don’t need to recompile after you make changes
◦ Same script will work on any operating system with MATLAB
 Disadvantages
◦ Because code is compiled on the fly, some tasks can be slow*
◦ Others can change your code*

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 4


Matlab Screen

 Command Window
◦ type commands

 Current Directory
◦ View folders and m-files

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

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 5


Algorithm Example

 Before starting to write any code, you should break the


problem down into a simple algorithm
 Algorithm: A sequence of steps to solve a problem
 Example Algorithm: Calculate Volume of a Sphere
◦ Get the input: radius of sphere
◦ Calculate the result: volume of sphere
◦ Display the result
 Input typically comes from:
◦ The user typing in a value when prompted
◦ A file on your hard disk
 Output typically goes to:
◦ The screen (i.e. the MATLAB command window)
◦ A file on your hard disk
Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 6
Algorithm Example

Example Algorithm: Calculate Volume of a Sphere


1. Get the input: radius of sphere
◦ Set the radius
◦ Store the radius in a variable
2. Calculate the result: volume of sphere
◦ Plug radius into volume equation
◦ Store result in variable
3. Display the result
◦ We’ll do this later…

prompt = "Enter the value of the Radius in mm? ";


r = input(prompt);
V = (4/3) *pi*r^3;
disp(['The sphere volume is ',num2str(V),' mm^3'])
Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 7
MATLAB Variables

 Variable names must start with a letter, may contain only letters,
numbers and the underscore.
 Variable names are case sensitive, “time”, “Time”, and “TIME”
are all different variable names.
 Variable names can be up to 63 characters long.
 Stay away from using MATLAB key words as variable names,
“pi”, “i” or “j”, and MATLAB function names like “sqrt”, “sin”,
“mean”, “max”, etc.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 8


Working with Matrices

 MATLAB’s versatility and power come from its ability to work


with matrices.
 Engineering problems can be set up using matrix notation
 MATLAB simplifies matrix manipulations and hence simplifies
writing programs to solve engineering problems.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 9


Working with Matrices II

 Matrices can be
◦ Row vectors, [ 1, 2, 6, 15, 3, 6]
◦ Rectangular matrices, n rows and m columns
◦ Column vectors, [1; 5; 7; 11]
Matrices can be assigned variable names,
x = [1, 2, 7, 3]
“ ' ” is the complex conjugate transpose operator in MATLAB
 At first, working with matrices and formulating problems this
way will seem unnatural, but soon you will catch on and it will
become second nature for you.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 10


Scalar Operations

 Although matrices are key, we will continue to need to


work with scalars and particularly with scalars and
matrices together.
 Scalar operations
◦ Addition and Subtraction ( + and - )
◦ Multiplication and division ( * and / )
◦ Exponentiation ( ^ , 3^2 = 9 )

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 11


Operators (arithmetic)

+ addition
- subtraction
* multiplication
/ division
^ power
‘ complex conjugate transpose

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 12


Mathematical Operations

 Some examples of scalar operations


a=3
b=a+1
c=2*b
d = a/c + 5
x=1
x=x+1
 ' = ' is called the assignment operator. The right_hand_side is
evaluated and its value is assigned to the left_hand_side

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 13


Supressing Echoes

 Note on the previous slide, each line except the last one is
followed by a semi-colon. MATLAB will echo the result of each
line in the Command Window unless you request to suppress it.
Use the semi-colon to suppress the output except for the results
that you specifically want to have output.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 14


Variables

 No need for types ie,

int a;
double b;
float c;

 All variables are created with double precision unless specified


and they are matrices
Example:
>>x=5;
>>x1=2;

 After these statements, the variables are x, x1 matrices with


double precision

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 15


Array, Matrix

 a vector x = [1 2 5 1]

x =
1 2 5 1

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

x =
1 2 3
5 1 4
3 2 -1

 Transpose y = x’ y =
1
2
5
1

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 16


Long Array, Matrix

 t =1:10

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

k =
2 15 1 05 0 -05 -1

 B = [1:4; 5:8]

x =
1 2 3 4
5 6 7 8

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 17


Generating Vectors from functions

 zeros(M,N) MxN matrix of zeros


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

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 18


Matrix Index

 The matrix indices begin from 1 (not 0 (as in C))


 The matrix indices must be positive integer

Given:

A(-2), A(0)

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

A(4,2)
Error: ??? Index exceeds matrix dimensions

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 19


Concatenation of Matrices

 x = [1 2], y = [4 5], z=[ 0 0]

A = [ x y]

1 2 4 5

B = [x ; y]

1 2
4 5

C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 20


Matrices Operations

Given A and B:

Addition Subtraction Product Transpose

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 21


Operators (Element by Element)

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

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 22


The use of “” – “Element” Operation

A = [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
3 2 -1

x = A(1,:) y = A(3 ,:) b = x .* y c=x./y d = x. ^2

x= y= b= c= d=
1 2 3 3 4 -1 3 8 -3 033 05 -3 1 4 9

K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 23


Basic Task: Plot the function sin(x) between 0≤x≤4π

 Create an x-array of 100 samples between 0 and 4π

>>x=linspace(0,4*pi,100);

 Calculate sin() of the x-array


>>y=x.sin(x);

 Plot the y-array

>>plot(y)

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 24


Plot the function e-x/3sin(x) between 0≤x≤4π

 Create an x-array of 100 samples between 0 and 4π


>>x=linspace(0,4*pi,100);

 Calculate sin() of the x-array


>>y=sin(x);
 Calculate e-x/3 of the x-array
>>y1=exp(-x/3);

 Multiply the arrays y and y1


>>y2=y.*y1;

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 25


Plot the function e-x/3sin(x) between 0≤x≤4π

 Multiply the arrays y and y1 correctly


>>y2=y.*y1;
 Plot the y2-array
>>plot(x,y2)

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 26


Display Facilities

 plot() 0.7

0.6

0.5

Example: 0.4

>>x=linspace(0,4*pi,100); 0.3

>>y=sin(x); 0.2

>>plot(y)
0.1

>>plot(x,y) -0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100

 stem() 0.7

0.6

0.5

0.4

0.3

Example:
0.2

0.1
>>stem(y) 0

>>stem(x,y) -0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 27


Display Facilities

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

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 28


Display Facilities

 title()
>>title(‘This is the sinus function’)

 xlabel() 1
This is the sinus function

0.8

>>xlabel(‘x (secs)’)
0.6

0.4

0.2

 ylabel()

sin(x)
0

-0.2

>>ylabel(‘sin(x)’)
-0.4

-0.6

-0.8

-1
0 10 20 30 40 50 60 70 80 90 100
x (secs)

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 29


Operators (relational, logical)

 == Equal to
 ~= Not equal to
 < Strictly smaller
 > Strictly greater
 <= Smaller than or equal to
 >= Greater than equal to
 && And operator
 || Or operator

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 30


Flow Control

 if
 for
 while
 break
 …

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 31


Control Structures

 If Statement Syntax
Some Dummy Examples
if (Condition_1) if ((a>3) & (b==5))
Matlab Commands Some Matlab Commands;
elseif (Condition_2) end

Matlab Commands if (a<3)


elseif (Condition_3) Some Matlab Commands;
elseif (b~=5)
Matlab Commands Some Matlab Commands;
else end
Matlab Commands if (a<3)
end Some Matlab Commands;
else
Some Matlab Commands;
end

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 32


Control Structures

 For loop syntax


Some Dummy Examples

for i=Index_Array for i=1:100


Some Matlab Commands;
Matlab Commands end
end for j=1:3:200
Some Matlab Commands;
end

for m=13:-02:-21
Some Matlab Commands;
end

for k=[01 03 -13 12 7 -93]


Some Matlab Commands;
end

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 33


Control Structures

 While Loop Syntax

while (condition)
Matlab Commands Dummy Example
end
while ((a>3) & (b==5))
Some Matlab Commands;
end

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 34


Switch-case Selection

 Switch conditional structures is particularly useful when dealing


with some kind of menu where a variable can take a set of values
and various actions must take place accordingly.
 The syntax is:
switch variable
case value1
do this
case value2
do that

end;

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 35


Example of using switch

day=4; %This corresponds to Thursday=4th day


%after Monday
switch day
case 1 %this effectively means if day==1
disp(‘Today is Monday);
case 2 % i. e. if day==2
disp(‘Today is Tuesday’);

otherwise
disp(‘The number should be between 1 and 7’)
end;
 Note: The otherwise statement is optional. If it isn’t there and the
variable doesn’t take any of the case values tested then Matlab
reaches end and nothing has happened.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 36


Matlab editor

 Like any other source code, Matlab programmes (m-files) are


simply text files so you can use any text editor to read and edit
them.
 However the Matlab environment includes its own editor which
offers useful capabilities that other non-dedicated editors do not.
 3 ways to open a new m-file using Matlab editor
◦ Type >> edit myprogram.m at the command prompt
◦ Click on the blank page on Matlab main window toolbar
◦ Click File → New → M-file

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 37


M-files

 Once the file is open with the editor, you can write matlab
commands in it. For instance the three lines:
x=0:0.1:4*pi;
y=sin(x);
plot(x,y);
 To execute them, save and name the file then type the name of the
file at the command prompt (you don’t need to type the
extension). For instance:
>>myprogram or >>myprogram.m

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 38


M-files (cont)

 This will only work if you have saved your m-file in the ‘working
directory’ – the directory where Matlab first looks to execute
programs.
 You can check the working directory in the current directory
frame (shared with Workspace) or by typing >>pwd
 Programs can also be executed directly from the editor by
clicking the buttom showing an arrow down next to a page on the
editor toolbar.
 Now change the range in the previous script so that it goes up to
6π and re-run the script.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 39


Use of M-File

Click to create a
new M-File

• Extension “m”
• A text file containing script or function or program to run

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 40


Thoughts on Functions

Why Make Functions?


 When a task is often repeated, functions save time
 Faster than using “prompt”
When Writing a Function…
 Start by sketching out the basic algorithm (pencil & paper)
 Write algorithm first as a script
◦ Difficult to troubleshoot functions because variables are local
 Once the script works, generalize it into a function
 Functions do not need to return a value
◦ Some functions make plots, print information, or write files
 If a function does not require an input argument
◦ It should probably be left as a script
 Remember that scripts can call functions multiple times

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 41


Writing a program in Matlab

 For more complex tasks than simple calculations or plots, writing


commands line by line at the command prompt becomes quickly
tedious.
 You can ‘feed’ Matlab with a whole sequence of commands at a
time by writing a Matlab programme.
 Programmes written for Matlab are called m-files because they
take the extension .m
 Because Matlab is a scripting language, m-files are also
sometimes scripts.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 42


Script M-files

 An M-file is an ASCII text file containing MATLAB statements


in the form of a program or function.
 You use the MATLAB editor to create, modify, and save your
programs in your MyMatlabfiles folder with file name file_name.
 M-files support MATLAB’s programming environment

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 43


Script M-files II

 Once you have completed writing and saving your


program, you can run it in the Command Window by
simply entering the name of the file where it is stored
following the Command Window prompt.
>> file_name
cause your program to be run and the results generated.
(You can also run programs directly from the Edit
Window.)

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 44


Cell Mode using the Editor

 This utility lets you divide a MATLAB program into cells, you
can then execute each cell individually or together with all the
cells.
 Use %%_ (_ means space) to identify the beginning of each cell.
Usually following %%_ is the cell name.
 Highlight the cell by moving the cursor to the cell.
 Click on Cell in the Editor tool bar to select a cell to perform a
function.
 Cell Mode is useful when debugging larger programs.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 45


Writing User Defined Functions

 Functions are m-files which can be executed by specifying some


inputs and supply some desired outputs
 The code telling the Matlab that an m-file is actually a function is

function out1=functionname(in1)
function out1=functionname(in1,in2,in3)
function [out1,out2]=functionname(in1,in2)

 You should write this command at the beginning of the m-file and
you should save the m-file with a file name same as the function
name

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 46


Writing User Defined Functions
 Examples
◦ Write a function : out=squarer (A, ind)
 Which takes the square of the input matrix if the input indicator is equal
to 1
 And takes the element-by-element square of the input matrix if the input
indicator is equal to 2
Same Name

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 47


Commenting

 Comments can be added to a program in Matlab using the sign


‘%’. Matlab ignores whatever comes after this sign on the same
line. For example:
x=0:0.1:2*pi %Defines a vector from 0 to 2pi by 0.1
steps
 You can write whatever you like after %.
 Commenting using the command line does really make sense but
it is important to comment m-files.
 Commenting is very important and is essential to any
programming. From now on, all your m-files should be
commented.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 48


Pause execution

 Sometimes slowing down the execution is done deliberately for


observation purposes You can use the command “pause” for this
purpose

pause %wait until any key


pause(3) %wait 3 seconds

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 49


User keyboard input

 When Matlab runs an m-file, it is not as easy to interact with the


flow of instructions as it was when typing them line by line at the
command prompt.
 Loading/Saving data-files is one way to get your program to
interact but sometimes it is useful to ask the user for an input as
you did with the ConvertTime.exe program last time.
 In Matlab, the keyword for the user to input some information via
the keyboard during the execution is input.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 50


Variable = input(‘question to the user?’);

 The line above shows how to use the keyword input.


 Such a statement will cause Matlab to display ‘question to the
user?’ at the command line (or whatever you chose to write
between the quote signs)
 It will wait for an answer.
 Once the return key is pressed by the user, it will store the answer
into Variable.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 51


Precedence of Arithmetic Operations

 MATLAB evaluates expressions from left to right in the


following operator order or precedence

Precedence Operation
1 Parentheses, innermost first
2 Exponentiation, left to right
3 Multiplication and division, l to r
4 Addition and subtraction, l to r

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 52


Precedence of Arithmetic Operations II

 Look at the following ( a=1, b=2, c=4, d=5 )

a + b/c + d evaluates to 6.50

(a + b)/c + d 5.75

(a + b)/(c+d) 0.333

a + b/(c+d) 1.222

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 53


Precedence of Arithmetic Operations III

 All four expressions are valid and correct depending upon the
problem you are solving.
 To avoid confusion when entering long expressions, break them
up into smaller statements and then combine the results. If in
doubt use parentheses to enforce your ordering.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 54


Saving your Work

 At times you may want to save all or some of the variables and
their values that you’ve created during a session. Later when you
return, you would like to return the Workspace Window to its
previous values and continue your work. To do this you would
use the MATLAB “save” and “load” commands in the Command
Window.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 55


Saving your Work III

 Rather than save all your variables and their values, you can
selectively save and restore by
>> save file_name A B C
◦ to save only the variables A, B, and C.
>> load file_name
 will restore the variables and values A, B, and C to the Workspace
Window

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 56


“Symbolic” toolbox allows you to:

 Enter expressions in symbolic form with symbolic data types.


 Expand or simplify symbolic expressions.
 Find symbolic roots, limits, minima, maxima, etc.
 Differentiate and integrate symbolic functions.
 Generate Taylor series of functions.
 Solve algebraic and differential equations symbolically.
 Solve simultaneous equations (even some nonlinear).
 Do variable precision arithmetic.
 Create graphical representations of symbolic functions.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Creating Symbolic Variables

 To use the symbolic toolbox, you must create symbolic variables.


 To create one symbolic variable, type:
𝑥 = 𝑠𝑦𝑚 ′𝑥′ ;
 You can also use the syms command:
𝑠𝑦𝑚𝑠 𝑥

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Creating Multiple Variables

 To create several symbolic variables, use the syms command as


follows:
syms K T P0
 This creates the symbolic variables K, T, and P0; execute the
command whos to check that this is indeed the case.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Creating a symbolic expression with symbolic variables

 To create an expression using existing symbolic variables, type:


>> P=P0*exp(K*T)
 This creates a symbolic expression that includes the exponential
function. It could represent the exponential growth of a
population.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Create Symbolic Functions

 Create symbolic functions with one and two arguments.


>> syms s(t) f(x,y)
 Both s and f are abstract symbolic functions. They do not
have symbolic expressions assigned to them, so the bodies
of these functions are s(t) and f(x,y), respectively.
 Specify the following formula for f.
>> f(x,y) = x + 2*y
 Compute the function value at the point x = 1 and y = 2.
>>f(1,2)

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 61


Manipulating symbolic expressions

 numden()
 expand()
 factor()
 collect()
 simplify()
 simple()
 poly2sym()

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


numden()

 The numden() command is used to separate the numerator and


denominator of a quotient.
 Use numden() on the following expression:
y=2*(x+3)^2/(x^3+6*x+9)
[numerator,denumerator]=numden(y)
numerator=
2*(x + 3)^2
denominator=
(x^3 + 6*x + 9)

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


expand()

 expand() is used to expand an expression by expanding the


products of factors in an expression.

 Expand the numerator of y:


Expand(y)
ans=
2*x^2 + 12*x + 18

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


factor()

 The factor() command is used to factor an expression into a


product of terms.

 Example: Factor the expression for the denominator.

>> denumerator = x^2 + 6*x + 9;

>> factor(denumerator)

ans =

[x + 3, x + 3]

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


simplify()

 The simplify() command uses the Maple simplification algorithm


to simplify each part of an expression.
 Enter the expression:
>> simplify(y)
ans =

(2*(x + 3)^2)/(x^3 + 6*x + 9)

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


solve()

 The solve() function sets an expression equal to zero, then solves


the equation for its roots.
>> E=x^2 -9;
solve(E)
ans =
-3
3

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Systems of equations

 When solving for multiple variables, it can be more convenient to


store the outputs in a structure array than in separate variables.
The solve function returns a structure when you specify a single
output argument and multiple outputs exist.
 Solve a system of equations to return the solutions in a structure
array.
>> syms u v
>> eqns = [2*u + v == 0, u - v == 1];
>> S = solve(eqns,[u v]);
 Access the solutions by addressing the elements of the structure.
>>S.u
>>S.v

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Substitution with subs()

 The subs() command allows you to substitute a symbol with


another symbol or assign a number to a variable.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Plotting symbolical functions

 Plotting symbolic functions in MATLAB is done with the fplot()


set of commands.
 The syntax of fplot() when y is a function of x is:
y=x^2-2*x+3;
>> fplot(y)

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Differentiation

 MATLAB allows you to differentiate symbolic functions with


the diff() command.
 The syntax of diff(), when f is a symbolic function of the variable
x and n is the order of the derivative to be determined, is:

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Integration

 MATLAB allows you to integrate symbolic functions with the


int() command. Either definite integrals, with assigned numeric or
symbolic bounds, or indefinite integrals (note that when you
compute indefinite integrals, the constant of integration does not
appear explicitly).

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Integration constant

 If you want to display the integration constant when applying the


int() function, you can do the following:
syms x y a
y = 2*x;
int(y,’a’,’x’)
ans =
x^2–a^2

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Exercises

 Use the symbolic toolbox to solve the following system of


equations:
◦ x + 2y - z = 4
◦ 3x + 8y + 7z = 20
◦ 2x + 7y + 9z = 23

 The velocity of a car is v = t^2 – 3t + 5. Find the displacement for


1<t<5 and the acceleration at t=1.5. Plot the equations for
distance, velocity, and acceleration on one graph.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Summary

 Creating Symbolic Expressions


◦ sym(‘x’), syms x, expressions i.e. e=sym(‘m*c^2’)
 Manipulation
◦ numden, expand, factor, collect, simplify, simple, poly2sym
 Solutions
◦ solve, subs
 Plotting
◦ ezplot, fplot
 Differentiation
◦ diff(y, ‘x’, n)
 Integration
◦ int(y, ‘x’, a, b)

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker


Simulink
Introduction

 In the last few years, Simulink has become the most widely used
software package in academia and industry for modeling and
simulating dynamical systems.
 Simulink environment encourages you to pose a question, model
it, and see what happens.
 You can move beyond idealized linear models to explore more
realistic nonlinear models. Thus, describing real-world
phenomena.
 It turns your computer into a lab for modeling and analyzing
systems.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 77


What is SIMULINK?

 SIMULINK is a tool for modeling, analyzing, and simulating a


wide variety of physical & mathematical systems, including those
with nonlinear elements and those which make use of continuous
and discrete time
 Applications can be found in Dynamic Control Systems, Signal
Processing, Communications, and other time-varying systems.
 It supports linear and nonlinear systems, modeled in continuous
time, sampled time, or a hybrid of the two.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 78


What is Simulink?

 For modeling, Simulink provides a graphical user interface (GUI)


for building models as block diagrams, using click-and-drag
mouse operations.
 With this interface, you can draw the models just as you would
with pencil and paper.
 You can also customize and create your own blocks.
 Models are hierarchical, so you can build models using both top-
down and bottom-up approaches.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 79


Starting Simulink

 You can start Simulink in two ways:

1. Click on the Simulink icon on the MATLAB toolbar.

2. Enter the simulink command at the MATLAB prompt.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 80


Editing an Existing Model

 To edit an existing model diagram, either:


 Choose the Open button on the Library Browser’s toolbar
(Windows only) or the Open command from the Simulink library
window’s File menu and then choose or enter the model filename
for the model you want to edit.
 Enter the name of the model (without the .mdl extension) in the
MATLAB command window. The model must be in the current
directory or on the path.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 81


What is Simulink?

 After you define a model, you can simulate it, using a choice of
integration methods, either from the Simulink menus or by
entering commands in MATLAB’s command window.
 You can change parameters and immediately see what happens,
for “what if” exploration.
 The simulation results can be put in the MATLAB workspace for
postprocessing and visualization

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 82


Quick Start

Running a Demo model


 An interesting demo program provided with Simulink models the
thermodynamics of a house.
 To run this demo, type thermo in the MATLAB command
window. This command starts up Simulink and creates a model
window that contains this model.
or
>> demo ‘simulink’

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 83


Quick Start

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 84


Quick Start

 When you open the model, Simulink opens a Scope block


containing two plots labeled Indoor vs. Outdoor Temp and Heat
Cost ($), respectively.
 To start the simulation, pull down the Simulation menu and
choose the Start command (or, on Microsoft Windows, press the
Start button on the Simulink toolbar).
 As the simulation runs, the indoor and outdoor temperatures
appear in the Indoor vs. Outdoor Temp plot and the cumulative
heating cost appears in the Heat Cost ($) plot.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 85


Quick Start

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 86


Quick Start

 To stop the simulation, choose the Stop command from the


Simulation menu (or press the Pause button on the toolbar).
 When you’re finished running the simulation, close the model by
choosing Close from the File menu.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 87


Quick Start

Description of the Demo


 The demo models the thermodynamics of a house using a simple
model. The thermostat is set to 70 degrees Fahrenheit and is
affected by the outside temperature, which varies by applying a
sine wave with amplitude of 15 degrees to a base temperature of
50 degrees. This simulates daily temperature fluctuations.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 88


Quick Start

 The model uses subsystems to simplify the model diagram and


create reusable systems.
 A subsystem is a group of blocks that is represented by a
Subsystem block.
 This model contains five subsystems: Thermostat, House, and
three Temp Convert subsystems (two convert Fahrenheit to
Celsius, one converts Celsius to Fahrenheit).

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 89


What this Demo Illustrates?

 Running the simulation involves specifying parameters and


starting the simulation with the Start command.

 You can encapsulate complex groups of related blocks in a single


block, called a subsystem.

 You can create a customized icon and design a dialog box for a
block by using the masking feature.

 Scope blocks display graphic output much as an actual


oscilloscope does.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 90


Building a Simple Model

 The model integrates a sine wave and displays the result, along
with the sine wave.

 To create the model, first type simulink in the MATLAB


command window.

 Note: The window might differ based on the operating system


you are using.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 91


Summary of Mouse and Keyboard Actions

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 92


Summary of Mouse and Keyboard Actions

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 93


Summary of Mouse and Keyboard Actions

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 94


Summary of Mouse and Keyboard Actions

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 95


Building a Simple Model

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 96


Building a Simple Model

 To create a new model, select the New Model button on the


Library Browser’s toolbar.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 97


Building a Simple Model

 To create this model, you will need to copy blocks into the
model from the following Simulink block libraries:
◦ Sources library (the Sine Wave block)

◦ Sinks library (the Scope block)

◦ Continuous library (the Integrator block)

◦ Signals & Systems library (the Mux block)

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 98


Building a Simple Model

 To copy the Sine Wave block from the Library Browser, first
expand the Library Browser tree to display the blocks in the
Sources library. Do this by clicking first on the Simulink node to
display the Sources node, then on the Sources node to display the
Sources library blocks. Finally click on the Sine Wave node to
select the Sine Wave block.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 99


Building a Simple Model

 Now drag the Sine Wave node from the browser and drop it in the

model window.

 Copy the rest of the blocks in a similar manner from their

respective libraries into the model window.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 100


Building a Simple Model

 Now it’s time to connect the blocks. Connect the Sine Wave block
to the top input port of the Mux block. Position the pointer over
the output port on the right side of the Sine Wave block.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 101


Building a Simple Model

 Drawing a branch line is slightly different. To weld a connection

to an existing line, follow these steps:

 First, position the pointer on the line between the Sine Wave and

the Mux block.

 Second, Press and hold down the Ctrl key. Press the mouse

button, then drag the pointer to the Integrator block’s input port or

over the Integrator block itself.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 102


Building a Simple Model

 Finish making block connections. When you’re done, your model


should look something like this.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 103


Building a Simple Model

 Now, open the Scope block to view the simulation output.

Keeping the Scope window open, set up Simulink to run the

simulation for 10 seconds.

 First, set the simulation parameters by choosing Parameters from

the Simulation menu.

 On the dialog box that appears, notice that the Stop time is set to

10.0 (its default value).

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 104


Building a Simple Model

 Set the initial condition in the integrator block to -1.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 105


Creating Subsystems

As your model increases in size and complexity, you can simplify
it by grouping blocks into subsystems. Using subsystems has
these advantages:
1. It helps reduce the number of blocks displayed in your model
window.
2. It allows you to keep functionally related blocks together.
3. It enables you to establish a hierarchical block diagram, where a
Subsystem block is on one layer and the blocks that make up the
subsystem are on another.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 106


Creating Subsystems

 You can create a subsystem in two ways:


1. Add a Subsystem block to your model, then open that block and
add the blocks it contains to the subsystem window.
2. Add the blocks that make up the subsystem, then group those
blocks into a subsystem.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 107


Tips for Building Models

Here are some model-building hints you might find useful:


 Memory issues: In general, the more memory, the better Simulink
performs.
 Using hierarchy: More complex models often benefit from adding
the hierarchy of subsystems to the model. Grouping blocks
simplifies the top level of the model and can make it easier to
read and understand the model.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 108


Tips for Building Models

 Cleaning up models: Well organized and documented models are


easier to read and understand.
 Modeling strategies: If several of your models tend to use the
same blocks, you might find it easier to save these blocks in a
model. Then, when you build new models, just open this model
and copy the commonly used blocks from it. You can create a
block library by placing a collection of blocks into a system and
saving the system. You can then access the system by typing its
name in the MATLAB command window.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 109


Modeling Equations

 One of the most confusing issues for new Simulink users is how
to model equations. Here are some examples that may improve
your understanding of how to model equations.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 110


Modeling Equations

 Converting Celsius to Fahrenheit


 To model the equation that converts Celsius temperature to
Fahrenheit:
TF = 9/5(TC) + 32
 First, consider the blocks needed to build the model:
 A Ramp block to input the temperature signal, from the Sources
library
 A Constant block, to define a constant of 32, also from the
Sources library
 A Gain block, to multiply the input signal by 9/5, from the Math
library

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 111


Modeling Equations

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 112


Modeling Equations

 A Sum block, to add the two quantities, also from the Math
library
 A Scope block to display the output, from the Sinks library
 Next, gather the blocks into your model window.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 113


Modeling Equations

 The Ramp block inputs Celsius temperature. Open that block and
change the Initial output parameter to 0.
 The Gain block multiplies that temperature by the constant 9/5.
The Sum block adds the value 32 to the result and outputs the
Fahrenheit temperature.
 Open the Scope block to view the output. Now, choose Start from
the Simulation menu to run the simulation. The simulation will
run for 10 seconds.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 114


Modeling Equations

Modeling a Simple Continuous System


 To model the differential equation
𝑥ሶ 𝑡 = −2𝑥 𝑡 + 𝑢(𝑡)
 where u(t) is a square wave with an amplitude of 1 and a
frequency of 1 rad/sec.
 The Integrator block integrates its input, x’, to produce x.
 Other blocks needed in this model include a Gain block and a
Sum block.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 115


Modeling Equations

 To generate a square wave, use a Signal Generator block and


select the Square Wave form but change the default units to
radians/sec. Again, view the output using a Scope block. Gather
the blocks and define the gain.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 116


Modeling Equations

 In this model, to reverse the direction of the Gain block, select the
block, then use the Flip Block command from the Format menu.
Also, to create the branch line from the output of the Integrator
block to the Gain block, hold down the Ctrl key while drawing
the line.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 117


Modeling Equations

 An important concept in this model is the loop that includes the


Sum block, the Integrator block, and the Gain block.
 In this equation, x is the output of the Integrator block. It is also
the input to the blocks that compute x’, on which it is based. This
relationship is implemented using a loop.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 118


Modeling Equations

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 119


Lets Get Familiar

 Modeling a second order ODE.


 Consider the following model
𝑑2 𝑥 𝑑𝑥
2
+3 + 4𝑥 = 5 cos 2𝑡
𝑑𝑡 𝑑𝑡
𝑥 0 =0
𝑑𝑥
0 =0
𝑑𝑡

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 120


Lets Get Familiar

 Preparation
𝑑2 𝑥 𝑑𝑥
2
= 5 cos 2𝑡 − 3 − 4𝑥
𝑑𝑡 𝑑𝑡

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 121


Lets Get Familiar

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 122


Hidden Functions

 Many math Functions do NOT have their own block.


 Instead they “Hide” in a PullDown menu in another icon.
 Examine Some of These.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 123


Simscape
Simscape

 Simscape provides an environment for modeling and


simulating physical systems spanning mechanical, electrical,
hydraulic, and other physical domains.
 It provides fundamental building blocks from these domains that
you can assemble into models of physical components, such as
electric motors, inverting op-amps, hydraulic valves, and ratchet
mechanisms

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 125


Simscape: Key Features

 Single environment for simulating multidomain physical systems


with control algorithms in Simulink
 Physical modeling blocks covering more than 10 physical
domains, including mechanical, electrical, hydraulic, and two-
phase fluid
 Specialized solver technology for real-time simulation and
hardware in the loop (HIL) testing
 Physical units for parameters and variables, with all unit
conversions handled automatically
 Support for C-code generation (with Simulink Coder )

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 126


Simscape

 When you type ssc_new at the MATLAB Command prompt, the


software creates a new model
 prepopulated with certain blocks.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 127


Simscape

 ssc_dcmotor

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 128


Essential Steps for Constructing a Physical Model

 Step 1: Create New Model Using ssc_new


 Step 2: Assemble Physical Network
 Step 3: Adjust Block Parameters and Variable Targets
 Step 4: Add Sources
 Step 5: Add Sensors
 Step 6: Connect to Simulink with Interface Blocks”
 Step 7: Simulate Model
 Step 8: View Simulation Results

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 129


Essential Steps for Constructing a Physical Model

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 130


Simscape-Electrical Library

Electrical Elements

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 131


Simscape-Electrical Library

 The Current Sensor block represents an ideal current sensor, that


is, a device that converts current measured in any electrical
branch into a physical signal proportional to the current.
 The Voltage Sensor block represents an ideal voltage sensor, that
is, a device that converts voltage measured between two points of
an electrical circuit into a physical signal proportional to the
voltage.

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 132


Simscape-Electrical Library

Electrical Sources

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 133


Simscape-Electrical Library

 The PS-Simulink Converter block converts a physical signal into


a Simulink® output signal. Use this block to connect outputs of a
Physical Network diagram to Simulink scopes or other Simulink
blocks.
 The Simulink-PS Converter block converts the input Simulink®
signal into a physical signal. Use this block to connect Simulink
sources or other Simulink blocks to the inputs of a Physical
Network diagram.

Utilities

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 134


Simscape-Electrical Library

 Each physical network represented by a connected Simscape


block diagram requires solver settings information for simulation.
The Solver Configuration block specifies the solver parameters
that your model needs before you can begin simulation.
 Each topologically distinct Simscape block diagram requires
exactly one Solver Configuration block to be connected to it.
 The block has one conserving port. You can add this block
anywhere on a physical network circuit by creating a branching
point and connecting it to the only port of the Solver
Configuration block.
Utilities

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 135


Simscape-Electrical Library

Example 1

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 136


Simscape-Electrical Library

This is a single network Example 2


that has its distinct
Solver Configuration
Block This is a separate
network that must have a
distinct Solver
Configuration Block

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 137


Simscape-Electromechanical system

Mansoura University Fundamentals of Mechatronics Engineering Dr. Ahmed Asker 138

You might also like