Вы находитесь на странице: 1из 60

Table of Contents

Day 1: Getting Started with MATLAB ............................................................................................................ 3 


1.1  What is MATLAB software? ........................................................................................................... 3 
1.2  What can we do using the MATLAB? ............................................................................................. 3 
1.3  Starting the MATLAB. .................................................................................................................... 4 
1.4  MATLAB platform interface components. ...................................................................................... 4 
1.5  Defining variables in the MATLAB and basic MATLAB commands. ........................................... 6 
1.6  Some important constants in MATLAB. ......................................................................................... 9 
1.7  Getting help in MATLAB .............................................................................................................. 10 
1.8  MATLAB commands used in simple computations. ..................................................................... 11 
1.9  MATLAB commands used in matrices computations. .................................................................. 12 
Day 2: Writing simple MATLAB programs .................................................................................................. 15 
2.1  MATLAB commands used in complex number computations ...................................................... 15 
2.2  MATLAB commands used for 2-D plotting and 3-D plotting. ...................................................... 15 
2.3  Opening, saving and managing M-files. ........................................................................................ 18 
2.4  Writing a MATLAB function. ....................................................................................................... 23 
2.5  Basic flow-control in MATLAB. ................................................................................................... 24 
2.5.1  while loop ............................................................................................................................... 24 
2.5.2  for loop ................................................................................................................................... 24 
2.5.3  if, elseif, else ........................................................................................................................... 26 
2.6  Some symbolic computations. ....................................................................................................... 27 
Day 3: Getting Started with SIMULINK ....................................................................................................... 30 
3.1  What is the SIMULINK? ............................................................................................................... 30 
3.2  What can we do using the SIMULINK? ........................................................................................ 30 
3.3  Starting the SIMULINK. ................................................................................................................ 30 
3.4  Working with Demos. .................................................................................................................... 32 
3.5  Opening important libraries. .......................................................................................................... 35 
3.6  Building a simple model. ............................................................................................................... 38 
Day 4: Building simple models using SIMULINK........................................................................................ 44 
4.1  Embedding MATLAB expressions and functions in the SIMULINK model. ............................... 44 


 
4.2  Exchanging data between the SIMULINK and MATLAB workspace. ......................................... 49 
4.3  The SimPowerSystems library. ...................................................................................................... 52 
4.4  Modeling simple electric circuits using the SimPowerSystems library. ........................................ 53 
Day 5: Exam .................................................................................................................................................... 57 


 
Day 1: Getting Started with MATLAB

1.1 What is MATLAB software?

MATLAB is a fourth-generation programming language* for technical computing. It is used for


computation, visualization, and programming. MATLAB is developed by Mathworks. MATLAB
is abbreviation for (matrix laboratory). Matrices are used as basic data elements in MATLAB.
* Fourth-generation programming languages can perform advanced programming tasks in which
large pieces of information are treated at once instead of dealing with bits and bytes which makes
the language more friendly, powerful and versatile. Fourth generation languages may be capable to
perform tasks such as data management, report generation, mathematical optimization, GUI
development, or web development.

More details about what is MATLAB for the students can be found on the following link
http://www.mathworks.com/academia/student_version/details.html

The official website for the MATLAB software is http://www.mathworks.com/. In this website,
you can find anything you need to know about the MATLAB.

1.2 What can we do using the MATLAB?

You can do with the MATLAB more than you can count or imagine. Things that can be done
using the MATLAB may be grouped under the following items
‐ Mathematical computation and matrix manipulations.
‐ Implementing algorithms (writing MATLAB programs that perform specific tasks).
‐ Based on the previous two items, Mathematical modeling (creating models) and
optimization can be done using MATLAB.
‐ Statistical data analysis and data management (examples of data management includes data
sorting and data filtering).
‐ Visualizing data (plotting of functions and data).
‐ Creating user interfaces.
‐ Interfacing with other software and programming languages such as excel, C++, and JAVA.
‐ Symbolic computation.
‐ Report generation.
‐ Hardware Interface and control.

MATLAB is very strong in computational mathematics. Examples of mathematical calculations


that can be done using the MATLAB includes

‐ Algebraic Equations and nonlinear functions.


‐ Matrix computation and Linear Algebra.


 
‐ Numerical Calculations.
‐ Calculus and Differential Equations.
‐ Statistics.
‐ Integration.
‐ Transforms.

MATLAB has many built-in functions (Many toolboxes) that make the programming easy and
friendly. Examples of toolboxes in MATLAB are
‐ Control System Toolbox: Design and analyze control systems
‐ Data Acquisition Toolbox: Connect to data acquisition cards, devices, and modules
‐ DSP System Toolbox: Design and simulate signal processing systems
‐ Image Processing Toolbox: Perform image processing, analysis, and algorithm development
‐ Instrument Control Toolbox: Control and communicate with test and measurement
instruments
‐ Optimization Toolbox: Solve standard and large-scale optimization problems
‐ Signal Processing Toolbox: Perform signal processing, analysis, and algorithm development
‐ Simulink Control Design: Compute PID gains, linearize models, and design control systems
‐ Statistics and Machine Learning Toolbox: Perform statistical modeling and analysis
‐ Symbolic Math Toolbox: Perform symbolic math computations

Complete List of the toolboxes in MATLAB can be found in the following link
http://www.mathworks.com/products/

1.3 Starting the MATLAB.

After installing the MATLAB on your computer, the MATLAB is started by double clicking the
following icon

You can find this icon on the desktop and/or in the start menu\programs and/or in the following
path
C:\Program Files\MATLAB\R2007b\bin

1.4 MATLAB platform interface components.

Once the MATLAB is opened, you will see the following interface


 
Fig.1 MATLAB interface

The MATLAB interface has the following main components


‐ Command Window − This is the place where you write the MATLAB commands and see
the results. Each MATLAB command line starts with a command prompt (>>).
‐ Command history window− in which the commands executed previously by the MATLAB
are recorded. Double click on one command in the command history window and it will be
executed again.
‐ Workspace window− The workspace shows all the variables created in the MATLAB.
‐ Current directory window − This window allows you to access the working folders and
files

Changing the working folder can be done by clicking the button in the following figure. The
working folder is the folder where you save your work such as MATLAB code or workspace
variables. After clicking this button; browse for the folder you need, choose it and click Ok.


 
Fig.2 changing the working folder

1.5 Defining variables in the MATLAB and basic MATLAB commands.

Write in the MATLAB command window


>> x = 2 % this will define a variable x and initialize it with a value of 2

Then press “enter” in your keyboard. MATLAB will write the following
x=
2

MATLAB has created a 1 by 1 matrix with a name x and stored in it a value of 2. Now, you can
observe this variable in the workspace window.

Now, execute the following commands and see what will happen
>> sqrt(3)

MATLAB will respond with the following


>> ans =
1.7321

Since you did not create a variable, the MATLAB created one for you with a name “ans” and it
stored the results in the variable “ans”. Now, Try
>> 2+3

MATLAB will respond with the following


>> ans =
5

When you define a variable and press enter, the MATLAB rewrite it on the command window. To
prevent this, add a semicolon as follow


 
>> z=3;

After writing the above command and pressing enter, the MATLAB will not display anything;
however, observe that a variable with name “z” has been created in the workspace window and has
been assigned a value of 3. Now, defined more than one variable and perform a simple
computation as follow
>> a=3;
>> b=25*2;
>> c= a^3+b

MATLAB will respond with the following


c=
77

Now perform the following simple computation


>> c= a^(3+b)

MATLAB will respond with the following


c=
1.9383e+025

MATLAB evaluates an expression according to the precedence levels of the operators. The
precedence levels of the main operators from the highest to the lowest is as follows
1. Parentheses “( )”
2. Power “^”
3. Multiplication “*” and division “/”
4. Addition “+” and subtraction “-“

Operators have the same precedence level are evaluated from the left to the right. Now, what do
you expect to be the result of the following computation?
>> a=1;
>> b=2;
>> c= 4;
>> d=a*c^2/b+a-b*(c-b)

MATLAB answer will be


d=
5

If you forget the variable you have defined in MATLAB, use the command who or whos to get a
list of the variables defined in the work space
>> who


 
MATLAB answer will give you the variables defined in your workspace
Your variables are:
a b c d

The command whos provides you with more details


>> whos

MATLAB answer will be


Name Size Bytes Class Attributes

a 1x1 8 double
b 1x1 8 double
c 1x1 8 double
d 1x1 8 double

If you need to clear the command window, use the command “clc” which will delete all the
commands and answers written in the command window. Please, note that the previous executed
commands are still available in the command history window.
>> clc % to clear the command window

To delete the variables you have defined in the workspace, use the command “clear”
>> clear % to clear the workspace

Now, let us define more basic data elements such as vectors and matrices. To define a row vector,
write for example
>> row=[1 2 3 4]

MATLAB will display


row =
1 2 3 4

To define a column vector, write for example


>> column=[7;8;9;10]

MATLAB will display


column =
7
8
9
10

To define the following matrix in MATLAB


 
2 3 4 
 
a  5 6 7 
 8 9 10 
 
Write the following command and press enter
>> a=[2 3 4;5 6 7;8 9 10]

The MATLAB will display the matrix “a” since you did not put a semicolon at the end of the
command. You will observe also that MATLAB has added a matrix in the workspace with a name
“a”.
a=
2 3 4
5 6 7
8 9 10

Now, define a second matrix “b” and multiply “a” by “b” as follows
>> b=[5 1 2;3 4 6;6 5 7];
>> c=a*b

The answer will be as follows


c=
43 34 50
85 64 95
127 94 140

1.6 Some important constants in MATLAB.


Important constants in MATLAB are inf, NaN, pi, realmax, and realmin. Type the following
>> inf+100

MATLAB answer is
ans =
Inf

Type the following


>> inf*100

MATLAB answer is
ans =
Inf


 
Type the following
>> 0/0

MATLAB answer is
ans =
NaN

Type the following


>> inf/inf

MATLAB answer is
ans =
NaN

Type the following


>> pi

MATLAB answer is
ans =
3.1416

Type the following


>> realmax

MATLAB answer is
ans =
1.7977e+308

Type the following


>> realmin

MATLAB answer is
ans =
2.2251e-308

1.7 Getting help in MATLAB


To get help about a certain MATLAB command such as “clear”, write

>> help clear

10 
 
MATLAB answer will provide you with all information you need about the command “clear”.
You can also use the command “doc” to get help about a certain MATLAB function such as
“clear”
>> doc clear

Write the command “doc” to open the MATLAB help window


>> doc

The following help window will open, in which you can browse for the topic you need help about
or search for this topic

Fig.3 MATLAB help window

1.8 MATLAB commands used in simple computations.


Table 1 lists some MATLAB functions used to perform simple computational processes.

Example 1: to calculate sin (90) in MATLAB, write the following command. Please, observe that
the sin argument should be in radians
>> sin(pi/2)

MATLAB answer will be


>> ans =

11 
 
1

Table 1 some MATLAB functions used to perform


simple computational processes
MATLAB
Operation
command
|x| (absolute value of x) abs(x)
square root of x sqrt(x)
exponential ex exp(x)
ln x (natural log) log(x)
log10 x (base 10 log) log10(x)
sin x sin(x)
cos x cos(x)
tan x tan(x)
cot x cot(x)
arcsin x asin(x)
arccos x acos(x)
arctan x atan(x)
arccot x acot(x)
n! (n factorial) factorial(3)

Example 2: to calculate 4! (factorial of 4), write in MATLAB


>> factorial(4)

MATLAB answer will be


>> ans =
24

1.9 MATLAB commands used in matrices computations.

Table 2 lists some MATLAB functions used to perform simple matrices operations

Example 1: to create a 5 by 5 random matrix, and get the inverse of this matrix; use the following
commands
>> y=rand(5,5)
>>x=inv(y)

To recall or extract certain elements of a matrix, follow the following examples


>> a=[1 2 3;4 5 6;7 8 9];
This will create the following matrix and save it in the MATLAB workspace

12 
 
 1 2 3
 
a   4 5 6
7 8 9
 

Table 2 some MATLAB functions used to perform simple matrices operations


MATLAB
Operation
command
Creates a matrix of m rows and n columns and all the
zeros(m,n)
elements are equal to zero
Creates a matrix of m rows and n columns and all the
ones(m,n)
elements are equal to one
Creates a matrix of m rows and n columns and all the
elements are generated randomly between zero and rand(m,n)
one
To take the transpose of a matrix y
transpose(y) or y’
(changing rows into columns)
To get inverse of a matrix y Inv(y)
To get the determinant of matrix y det(y)

To recall the element in the second row and third column, write the following in MATLAB
>> a(2,3)

MATLAB answer will be


ans =
6

To extract the third row, write the following in MATLAB


>> a(3,:)

MATLAB answer will be


ans =
7 8 9

To extract the second column, write the following in MATLAB


>> a(:,2)

MATLAB answer will be


ans =
2
5
8

13 
 
You can use the colon “:” to create vectors as follows
>> x=1:4

MATLAB answer will be


x=

1 2 3 4

Or you can create a vector with a certain step between the elements as follows
>> y=1:3:10

MATLAB answer will be


y=
1 4 7 10

14 
 
Day 2: Writing simple MATLAB programs

2.1 MATLAB commands used in complex number computations


To define a complex number in MATLAB, say 2+3i, write the following command in MATLAB

>>a=2+i*3

MATLAB answer will be


a=

2.0000 + 3.0000i

You can also use the following two commands to define the same complex number
>>a=complex(2,3)

Or
>>a=2+j*3

The following table lists MATLAB functions used in complex number computations.

Table 3 some MATLAB functions used in complex number computations


MATLAB
Operation
command
Returns the real part of complex number a real(a)
Returns the imaginary part of complex number a imag(a)
Gets the absolute value of a complex number a abs(a)
Gets the angle of a complex number a angle(a)
To find the conjugate number of complex number a conj(a)

Example: to get a conjugate number


>>a=2+i*3;
>>c=conj(a)

MATLAB answer will be as follows


c=
2.0000 - 3.0000i

2.2 MATLAB commands used for 2-D plotting and 3-D plotting.
2-D plotting in MATLAB can be done using plot command as in the following examples

>>x=1:1:20;
>>y=x;
>>plot(x,y)

15 
 
MATLAB will plot the following figure
20

18

16

14

12

10

0
0 2 4 6 8 10 12 14 16 18 20

Fig.4 example of MATLAB 2-d plot

Another example
>>wt=0.01:0.01:4*pi;
>> x=sin(wt);
>>y=cos(wt);
>>plot(wt,x,wt,y)

MATLAB will give the following figure


1

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 2 4 6 8 10 12 14

Fig.5 example of MATLAB 2-d plot

16 
 
Table 4 presents some MATLAB commands used in plotting.

Table 4 some MATLAB functions used in plotting


MATLAB
Operation
command
To add a label to the x-axis xlabel
To add a label to the y-axis ylabel
To add a title to the figure title
To add a legend to the figure legend
To add a grid to the figure grid on
To change the axis limits axis

Example
>>wt=0.01:0.01:4*pi;
>> x=sin(wt);
>>y=cos(wt);
>>plot(wt,x,wt,y)
>> grid on
>> legend('sin wave','cos wave')
>> axis([0 2*pi -1.5 1.5])
>> xlabel('wt')
>> ylabel('sin and cos values')
>> title(' sin and cos waves')

MATLAB will give the following figure


sin and cos waves
1.5
sin wave
cos wave
1

0.5
sin and cos values

-0.5

-1

-1.5
0 1 2 3 4 5 6
wt

Fig.6 example of a MATLAB 2-d plot

17 
 
To plot a 3-d plot in MATLAB, use the command plot3 as in the following example
>>t = 0:pi/50:10*pi;
>>x = sin(t);
>>y=cos(t);
>>plot3(t,x,y)

MATLAB will plot the following

0.5

-0.5

-1
1
0.5 40
0 30
20
-0.5 10
-1 0

Fig.7 example of a MATLAB 3-d plot

2.3 Opening, saving and managing M-files.


M-files are used in MATLAB for two purposes. The first purpose is to write a script file which is
a collection of MATLAB commands that you wish to execute together. The second purpose is to
write a MATLAB function which receives inputs and returns outputs. The variables defined in a
MATLAB function are local for this function.

To open an M-file, click on the button in the following figure

18 
 
Fig.8 Opening an M-file

Or do as shown in the following figure

Fig.9 Opening an M-file

A third method to open an M-file is to write the command edit in the command window

>>edit

As a result for any of the above mentioned methods, an M-file editor window will open as shown
in the following file. The M-file editor is used to create and manage an M-files.

19 
 
Fig.10 M-file editor window

In the M-file editor window, write the following set of commands as shown in the following figure

Fig.11 simple M-file script

20 
 
Before running the above script file, you need to save it first. You can save the file by clicking on
the save button as shown in the following figure

Fig.12 saving an M-file

Clicking on the save button will open the browse window shown in the next figure

Fig.13 saving an M-file


21 
 
If you need to save the M-file with another name different than the default name given by the
MATLAB, you have to consider the following while naming an M-file

 Use letters, numbers, or underscores to name an M-file


 Do not start a file name with a number
 Do not use a MATLAB keyword or function to name an M-file (such as for or end)
 Do not use a mathematical operator such as (- or +) in the file name.

The above rules are also valid for naming variables in MATLAB. If you need to check if a variable
name or M-file name is correct or not, use the MATLAB function isvarname. An example will
follow

>>isvarname 7_program

MATLAB will answer as follows


ans =
0

Zero value means that the above name is incorrect in MATLAB. If the name is correct, MATLAB
will respond by a value of one.

After saving the M-file with a correct name, you can run this file by clicking the run button as
shown in the following figure

Fig.14 running an M-file

22 
 
The result of running an M-file will be shown in the MATLAB command window. The result of
running the above M-file will be as follows
c=
40.1711

z=
80.3421

y=
24

2.4 Writing a MATLAB function.


Open an M-file editor, and write in it the code shown in the next figure.

Fig.15 an example of writing a MATLAB function

In the above figure, “T_P_converter” is the function name. This function receives two inputs
(celsius and pascal) and returns two outputs (kelvin and bar).

To save the above function, you should save the M-file with the same name as the function name
which is “T_P_converter”.

To use the above function after saving it, write the following code in the command window
>> celsius=15;
>> pascal=250000;
>> [temperature,pressure] = T_P_converter(celsius, pascal)

23 
 
MATLAB will give you the following answer
temperature =
288.1500

pressure =
2.5000

Now, call the function with different input values as follows


>> celsius=27.5;
>> pascal=21758;
>> [temperature,pressure] = T_P_converter(celsius, pascal)

MATLAB answer will be


temperature =
300.6500

pressure =
0.2176

2.5 Basic flow-control in MATLAB.

2.5.1 while loop


MATLAB syntax for a while loop is as follows
while expression is true
execute statements
end

MATLAB evaluates an expression, and as long as this expression is true, MATLAB will
repeatedly execute a group of statements. An example will follow

Open an M-file and write the code shown in Fig. 16

Save the M-file and run it, MATLAB will give the following answer in the command window
hello world
hello world
hello world
hello world

2.5.2 for loop


MATLAB syntax is as follows

24 
 
for index = values
execute statements
end

For loops are used to repeatedly execute a set of statements for a specified number of times

Fig.16 an example of using a while loop

Open an M-file and write the code shown in Fig. 17

Fig.17 an example of using a for loop

25 
 
Save the M-file and run it, MATLAB will give the following answer in the command window
hello world
hello world
hello world
hello world
hello world

2.5.3 if, elseif, else


MATLAB syntax is as follows
if expression 1 is true
execute statements
elseif expression 2 is true
execute statements
else
execute statements
end

Open an M-file and write the code shown in the following figure

Fig.18 an example of using an if, elseif, else statement

Save the M-file and run it, MATLAB will give the following answer in the command window

26 
 
x is between 5 and 10
value of x is : 7

Observe the use of the MATLAB function fprintf in the previous M-file. fprintf can be used to
display a numerical value of a certain variable within a sentence on the command window. For
more information on using the fprintf function or any function in MATLAB, you can use the
MATLAB command doc as explained at section (1.7) of this course.

2.6 Some symbolic computations.

One of the wonderful toolboxes in MATLAB is the symbolic math toolbox. This section provides
few examples on symbolic computations using MATLAB.

The following is an example of calculating the derivative of a certain function. Assume the
following function

f (t )  2  t 3  sin(t )
To calculate the derivative of the above function, write the following commands in MATLAB

>>syms t
>>f=2*t^3+sin(t);
>>diff(f)

MATLAB answer will be as follows


ans =

6*t^2+cos(t)

To calculate higher derivatives of a function f, use the command diff(f,n).


>> syms x
>>f=5*x^4;
>>a=diff(f,2)

MATLAB answer will be


a=

60*x^2

In order to differentiate a function with respect to a certain variable, see the following example
>> syms t x
>>f=3*x*t+x;
>>a=diff(f,'t')

27 
 
MATLAB answer will be
a=

3*x

If you need to differentiate a certain function (f) n times with respect to a certain variable x, use
the following expression diff(f,'x',n).

To calculate an indefinite integral of a certain function, follow the next example


>> syms x
>>f=2*x^2;
>>int(f)

MATLAB answer will be


ans =

2/3*x^3

To calculate a definite integral of a certain function, follow the next example


>> syms x
>>f=x^2;
>>int(f,0,2)

MATLAB answer will be


ans =

16/3

To perform an indefinite integral with respect to a certain variable, say ‘x’, use the command
int(f,’x’,a,b).
>> syms x t
>>f=3*x*t;
>>int(f,'x',0,2)

MATLAB answer will be


ans =
6*t

In order to plot a function in MATLAB, use the ezplot function as follows


>> syms x
>>f=x^3;
>>ezplot(f,[-6,6])

28 
 
MATLAB will plot the following
x3

200

150

100

50

-50

-100

-150

-200

-6 -4 -2 0 2 4 6
x

Fig.19 example of using ezplot function to plot f(x)=x3

Use the function subs to substitute a value in a certain function

>> syms x
>>f=3*x^3+exp(x);
>>subs(f, 5)

MATLAB answer will be


ans =

523.4132

You can solve equations in MATLAB using the command solve. Write in MATLAB the following
>> [x,y] = solve('x + 5*y = 7','x - 5*y = 5')

MATLAB answer will be


x=
6
y=
1/5

29 
 
Day 3: Getting Started with SIMULINK

3.1 What is the SIMULINK?


Simulink is a graphical programming environment for modeling, simulating and analyzing
dynamic systems. Simulink provides a graphical editor, block libraries, and solvers for modeling
and simulating dynamic systems. It is integrated with MATLAB, which enable you to embed
MATLAB algorithms into models and extract simulation results to MATLAB for further analysis.

3.2 What can we do using the SIMULINK?


You can simulate any dynamic system such as electric systems, mechanical systems, and thermal
systems. Simulating any system will enable studying and analyzing the behaviour of this system.

3.3 Starting the SIMULINK.


To start the Simulink, type the word simulink in the command window

>> simulink

The following SIMULINK interface will open

Fig.20 SIMULINK library browser window

30 
 
You can also start the SIMULINK by clicking on the button shown in the following figure

Fig.21 starting the SIMULINK

To open a graphical model editor, in which you can build the model you need to simulate, from the
SIMULINK library browser window click on file > new > model as shown in the following figure

Fig.22 opening a SIMULINK model editor

31 
 
A SIMULINK model editor will open as shown in the following figure

Fig.23 SIMULINK model editor

3.4 Working with Demos.


A MATLAB demo is an example of a MATLAB program (M-file) or a Simulink model provided
by the MATLAB developers. To open MATLAB demos, write the command demo in the
MATLAB command window.
>> demo

As a result, the following window will open

Fig.24 opening MATLAB demos

32 
 
To open demos for SIMULINK models, click on the word Simulink as shown in the following
figure. A list of all the Simulink Demos will open in the left pane of the window.

Fig.25 opening the Simulink demos

To open any Simulink Demo, click on the name of the model which will open a page that
describes the model as shown in Fig. 26. After that, click on “Open this model” link to see the
Simulink model as shown in Fig. 27.

Fig.26 selecting a Simulink Demo to open

33 
 
Fig.27 opening a Simulink

Once you click on “Open this model” link, the Simulink model will open as shown in Fig. 28.
You may choose to run the model, close the model, or save the model in order to modify it as
shown in Fig. 28.

Fig. 28 an example of a Simulink Demo

You can press the back button as shown in Fig. 27 to return back to the main list of Simulink
demos in order to see more examples of systems that you can simulate using the Simulink.

34 
 
3.5 Opening important libraries.
Open the SIMULINK library browser by writing Simulink in the MATLAB command window,
and then press enter. Click on the commonly used blocks link as shown in the following figure

Fig. 29 the commonly used blocks library

To open the math operations library click on Math operations link as shown in the following figure

Fig. 30 blocks of the Math Operations library

35 
 
Blocks of libraries such as Sinks, Sources, Continuous, Signal Routing, and User-Defined
functions library can be shown by the same way. See the following figures

Fig. 31 blocks of the Sinks library

Fig. 32 blocks of the Sources library

36 
 
Fig. 33 blocks of the Continuous library

Fig. 34 blocks of the Signal Routing library

37 
 
Fig. 35 blocks of the User-defined Functions library

3.6 Building a simple model.


To build a simple Model, Start a new Model as shown in the following figure

Fig. 36 starting a new model

38 
 
A new model will open as shown in the following figure

Fig. 37 a new model window

You will build your model in the new model window by dragging the blocks you need from the
library browser window to the new model window. (Or Right-click on the block and select “add to
…”. See the following figure.

Fig. 38 Adding blocks to start building a new model

39 
 
Now add the blocks in the following figure to the model window

Fig. 39 building a simple model

Now double click on the constant block to open the following window in which you will change
the Constant value from the default value of “1” to “5” and then press Ok.

Fig. 40 changing a parameter of a block

Now you need to connect the blocks together to build your model. You do that as shown in the
following figure.

40 
 
Fig. 41 connecting two blocks

After connecting all the blocks you will have the model shown in the following figure. In this
figure, click on save followed by run as shown.

Fig. 42 saving and running the model

After saving and running the model, you will get the results shown in the display block. See the
following figure.

41 
 
Fig. 43 viewing the results after running the model

Now build the model shown in the following figure

Fig. 44 an example of another simple model

Save the above model and run it. To see the results, double click on the scope model to open the
scope window in which you will see the output.

42 
 
Fig. 45 the scope window

After opening the scope window, press on the Autoscale button as shown in the following figure

Fig. 46 the scope window after pressing on the Autoscale button

43 
 
Day 4: Building simple models using SIMULINK

4.1 Embedding MATLAB expressions and functions in the SIMULINK model.


To add a mathematical expression to a SIMULINK model, use the Fcn block (shown in the
following Figure).

Fig. 47 Fcn block

The following example will explain the use of the Fcn block. Assume you have an input for which
you need to perform the following computation

x  (1  x)
f (x )  x
5
e
In the above expression x is the input and f(x) is the output. The Fcn block will be used to perform
the above computation.

44 
 
In the Fcn block, the input has to be given the symbol “u”. So the mathematical expression will be
as follows

u  (1  u )
f (u )  u
5
e
Let u=0.5, the following Simulink block will evaluate the above expression for an input value
equal to 0.5.

Fig. 48 an example for using the Fcn block

The SIMULINK model shown in Fig. 48 consists of a constant block, Fcn block, and display
block. After adding these blocks to a new SIMULINK model, connect them. After that, double
click on the constant block and write 0.5 in the constant value field, and then click on Ok. Double
click on the Fcn block and write the mathematical expression in the expression field as shown in
the next figure, and then press Ok. Run the model, and you will see the output on the display
block. As shown in Fig. 48, the result will equal to 0.2262.

45 
 
Fig. 49 adding an expression in the Fcn block.

In order to embed a MATLAB function inside a SIMULINK model, use the Embedded MATLAB
Function block (shown in the following Figure).

Fig. 50 Embedded MATLAB Function block.

46 
 
The following example will explain how to use the Embedded MATLAB Function block. Add
five blocks to a new SIMULINK model as shown in Fig. 51.

Fig. 51 an example for using the Embedded MATLAB Function block.

Double click on the Embedded MATLAB Function. As a result, an embedded MATLAB editor
window will open as shown in Fig.52.

Fig. 52 embedded MATLAB editor window

47 
 
Change the code written in Fig.52 to that written in Fig. 53, and press on the disk button to save.
Close the embedded MATLAB editor window, and observe the changes in the SIMULINK model
which is shown in Fig. 54.

Fig. 53 changing the code inside the embedded MATLAB editor window

Fig. 54 an example for using the Embedded MATLAB Function block.

48 
 
Connect the blocks and change the constant value of each constant block as shown in Fig. 55. Run
the model and the results are displayed in the display blocks as shown in Fig. 55.

Fig. 55 an example for using the Embedded MATLAB Function block.

4.2 Exchanging data between the SIMULINK and MATLAB workspace.


In order to read a signal from MATLAB into the SIMULINK, use the “From Workspace” block.
You can find this block in the Sources library. In the MATLAB command window, write the
following commands
>>t = [0:0.1:10]';
>>x = sin(t);
>>y = cos(t);

Build a new SIMULINK model as shown in Fig. 56. Double click on the “From Workspace”
block, and enter the array [t, x, y] in the data entry. The SIMULINK model will be as shown in
Fig. 56. Run the model; double click on the scope; and press on the autoscale button. You will see
the output as shown in Fig. 57.

49 
 
Fig. 56 using the From Workspace block

Fig. 57 the output as shown in the scope block

50 
 
In order to extract a signal from the SIMULINK into MATLAB, use the “To Workspace” block.
You can find this block in the Sinks library. Build a new model in the SIMULINK as shown in
Fig. 58. You should expect finding the Sine wave block in the sources library.

Fig. 58 using the To Workspace block

Double click on the “To Workspace” block. Change the variable name to x, and change the Save
format to Array as shown in Fig. 59. Press ok, and run the model.

Fig. 59 changing the parameters of the To Workspace block

51 
 
Go to the MATLAB main window, you will observe that two variables have been added to the
workspace. These two variables are tout and x. Now, write the following command in the
MATLAB command window.
>>plot(tout, x)

You will get the plot shown in Fig.60.

Fig. 60 Sine wave plot

4.3 The SimPowerSystems library.


SimPowerSystems library presents blocks and analysis tools for power systems related modelling
and simulation. The blocks are aggregated in sub-libraries as shown in Fig. 61. The
SimPowerSystems can be used to simulate power system components such as electric circuits,
single and three-phase machines, and power electronics circuits. The SimPowerSystems also
provides analysis tools to perform harmonic analysis, load flow, and other key electrical power
system analyses.

52 
 
Fig. 61 the SimPowerSystems library

To see the blocks inside any sub-library or library, click on the “+” sign.

4.4 Modeling simple electric circuits using the SimPowerSystems library.


In this section you will learn to model the circuit shown in Fig. 62.

53 
 
Ammeter 10 Ohm
A

10 Volt 10 Ohm V Voltmeter

Fig. 62 an example of a simple electric circuit

Open a new SIMULINK model. Add to this model the following blocks

‐ Powergui
‐ DC Voltage Source
‐ Series RLC Branch (add two of this block)
‐ Voltage Measurement
‐ Current Measurement
‐ Display (add two of this block)

The Powergui block is a necessary block to simulate any electric system in the SIMULINK.

You can find the above blocks in the libraries/sub-libraries presented in the following table

Table 5 Library/sub-library of each considered block


Block Library/sub-library
Powergui SimPowerSystems
DC Voltage Source SimPowerSystems/Electrical Sources
Series RLC Branch SimPowerSystems/Elements
Voltage Measurement SimPowerSystems/Measurements
Current Measurement SimPowerSystems/Measurements
Display Simulink/Sinks

Arrange the blocks as shown in Fig. 63. To rotate a block, right-click on this block and choose
Format, then Rotate block.

54 
 
Fig. 63 Building a simple electric circuit in the SIMULINK

Double click on the DC Voltage Source, and change the amplitude value to 10. Double click on
the Series RLC Branch. Change the branch type to R, and change the resistance value to 10 as
shown in Fig. 64.

Fig. 64 changing the parameters of the Series RLC Branch

55 
 
Connect the blocks as shown in Fig. 65. Run the model, and you can see the results on the display
blocks as shown in Fig. 65.

Fig. 65 simulating a simple electric circuit

56 
 
Day 5: Exam

Q1: What is the MATLAB function used for calculating the square root of a given number?

Q2: Evaluate the following expression in MATLAB when x=5, and y =7?

( y  5) 2
z 
ex
Q3: State the MATLAB functions used to clear the command window and to clear the workspace?

Q4: Mention two MATLAB functions that can be used to recall the variables defined in your
workspace?

Q5: Define the following matrix in MATLAB?

 5 2 3 0 
 
5 1 3 4
a  
 3 4 8 9 
 
 9  2 3 4 
Q6: Using MATLAB, calculate the inverse of the matrix a defined in Q4?

Q7: Recall the second column of the matrix a defined in Q4 using MATLAB?

Q8: Recall the third row of the matrix a defined in Q4 using MATLAB?

Q9: Recall the element in the second row and third column of the matrix a defined in Q4 using
MATLAB?

Q10: Evaluate the following expression in MATLAB?


y 

Q11: How do you open the help page of the MATLAB function abs?

Q12: Evaluate the following expression in MATLAB?

y  cos (45 )

Q13: Evaluate the following expression in MATLAB?

57 
 
ln (10)
y 
5!
Q14: Using MATLAB, calculate the transpose of the matrix a defined in Q4?

Q15: Using a suitable MATLAB function, create a matrix of 5 rows and 4 columns and all the
elements are equal to zero?

Q16: Using a suitable MATLAB function, generate a random matrix of 3 rows and 3 columns
where all the elements are generated randomly between zero and one?

Q17: using a suitable MATLAB command, create a vector which starts by 0 and ends by 200 with
a step of 2?

Q18: Find the conjugate number of the following complex number z in MATLAB?

z  5  6i
Q19: Create a vector t that starts from 0 to 2π, then plot x=cos(t) versus t using MATLAB.

Q20: For the figure obtained in Q19, add a label to the x-axis, a label to the y-axis, and a title to
the graph?

Q21: How do you verify if “myfirst_program” is a correct variable or file name in MATLAB?

Q22: Write a MATLAB script in which you define the following variables x=5, y=9, and z=10;
after that, use the script file to perform the following computations.

f  (x  z  y )  5

x
g 
z y

Q23: Write a MATLAB function that converts from Kelvin to Celsius.

Q24: Using a While statement, write a MATLAB script that displays the word “hello” on the
screen three times?

Q25: Using a For loop, write a MATLAB script that displays the word “hello” on the screen three
times?

Q26: Using MATLAB, find the derivative of the following function

58 
 
f (t )  2  t 3  cos(t )

Q27: Using MATLAB, find the forth derivative of the following function

f (t )  2  t 6

Q28: Using MATLAB, evaluate the following expression

x
7
dx

Q29: Using MATLAB, find the value of y in the following expression


4
y   x 2 dx
2

Q30: solve the following two equations using MATLAB

x y 6

3* x  4* y  16

Q31: What is the MATLAB command used to open the MATLAB Demos?

Q32: in which library do the following blocks exist? (Mention only one library that contains all
the blocks)

Q33: in which library do the following blocks exist?

Q34: in which library do the following blocks exist?

59 
 
Q35: in which library do the following blocks exist?

Q36: in which library do the following blocks exist?

Q37: Using SIMULINK, perform the following computation if x=0.5.

x
sin( x )  e 5
f (x ) 
x 2 1
Q38: Using the embedded MATLAB function, convert from Kelvin to Celsius and from Bar to
Pascal if the input temperature is 300.6 Kelvin and the input pressure is 0.21758 Bar?

Q39: Using suitable blocks, simulate a cosine wave in the SIMULINK and export it to MATLAB,
and do the opposite which is creating a cosine wave in the MATLAB and adding it to a
SIMULINK model.

Q40: Using SIMULINK, find the readings of the ammeter and voltmeter in the following circuit

Ammeter 2.5 Ohm
A

10 Volt 5 Ohm 5 Ohm V Voltmeter

60 
 

Вам также может понравиться