[go: up one dir, main page]

0% found this document useful (0 votes)
67 views120 pages

Course Name Simulation and Computational Laboratory: by Belaynesh Belachew (Lec.)

This document provides instructions and an overview for a Matlab simulation and computational laboratory course. The course will cover Matlab fundamentals, logical vectors, matrices, introduction to graphics, loops, Simulink, and applications in electrical fields. Students will learn how to define variables, perform calculations, and create graphs in Matlab. They will then use these skills to develop script files to solve more complex models. Topics will include Matlab basics, commands, functions, logical operations, and using the find function for logical expressions. The goal is to familiarize students with using Matlab for technical computing and simulations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views120 pages

Course Name Simulation and Computational Laboratory: by Belaynesh Belachew (Lec.)

This document provides instructions and an overview for a Matlab simulation and computational laboratory course. The course will cover Matlab fundamentals, logical vectors, matrices, introduction to graphics, loops, Simulink, and applications in electrical fields. Students will learn how to define variables, perform calculations, and create graphs in Matlab. They will then use these skills to develop script files to solve more complex models. Topics will include Matlab basics, commands, functions, logical operations, and using the find function for logical expressions. The goal is to familiarize students with using Matlab for technical computing and simulations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 120

Course Name

Simulation and Computational Laboratory


Course Code EP-2122
Credit hours 1-0-3

By
Belaynesh Belachew (Lec.)
Lab Instructions

When you attend to this lab you must follow the following
instructions:
1. Attend on your time, not before not after;
2. Try to use the same computer every time ;
3. Make a folder with your name and save the programs you
perform at this folder, (this important for your evaluation).

09/13/2021 Defence univerisity,Collage of Engineering 2


Goal
• The goal of this tutorial is to familiarize you with the fundamentals of
Matlab (defining variables, doing calculations and creating graphs). In our
next session, we will use these fundamentals to develop Matlab script files
(programs) to solve more complicated models

09/13/2021 Defence univerisity,Collage of Engineering 3


Topics to be covered

• Introduction
• Matlab fundamentals
• Logical Vectors
• Matrices
• Introduction to graphics
• Loops
• Simulink
• Application of Matlab in the field of electrical

09/13/2021 Defence univerisity,Collage of Engineering 4


Introduction to Matlab

• MATLAB is a high performance language for technical computing. It integrates


computation, visualization and programming in an easy-to-use environment where
problems and solutions are expressed in familiar mathematical notation.
• MATLAB is numeric computation software for engineering and scientific
calculations.
• MATLAB is primary tool for matrix computations.
• MATLAB is being used to simulate random process, power system, control system
and communication theory.
• MATLAB comprising lot of optional tool boxes and block set like control system,
optimization, and power system and so on.

09/13/2021 Defence univerisity,Collage of Engineering 5


Some of the strengths of Matlab are:

• Flexibility to solve a large number of problems

• Good tools for visualization


• Can be used on most computer systems (Mac, PC, Unix Workstation, Cray, ...)

• Used at many colleges, universities and industry in many different disciplines


(science, math, computer science, finance)
• The scripting language is relatively easy to learn, and is complementary with
traditional programming languages (BASIC, FORTRAN, C, Pascal)

09/13/2021 Defence univerisity,Collage of Engineering 6


What can we use Matlab for?

• Simple calculations

• Plotting and analyzing mathematical relationships (2D and 3D)


• List & Matrix Operations

• Writing script files (a type of programming)


• Symbolic manipulation of equations

09/13/2021 Defence univerisity,Collage of Engineering 7


How to run, interrupt, and terminate MATLAB?

09/13/2021 Defence univerisity,Collage of Engineering 8


Starting MATLAB
• When you start MATLAB, a special window called the MATLAB desktop appears.
The desktop is a window that contains other windows. The major tools within or
accessible from the desktop are The Command Window

• Window Purpose

Command window main window, enter variables, run programs


Figure window contains output from graphic commands
Editor window creates and debugs script and function files
Help window provides help information
Command history window & logs commands entered in the command

window
Workspace window provides information about the variables
that are used
Current Folder shows the files in the current directory
09/13/2021 Defence univerisity,Collage of Engineering 9
09/13/2021 Defence univerisity,Collage of Engineering 10
MATLAB Basics
• In MATLAB, every expression, or variable, has a type associated with it.By
default, numbers are stored as the type double(short for double-precision).The
type char is used to store either single characters (e.g., ‘x’) or strings, which are
sequences of characters (e.g., ‘cat’). Both characters and strings are enclosed in
single quotes.The type logical is used to store true/false values.
• MATLAB uses double-precision floating point arithmetic accurate to
approximately 15 digits, however,only 5 digits are displayed, by default. To
display more digits, type format long. Then all subsequent numerical output will
have 15 digits displayed. Type format short to return to 5-digit display.

09/13/2021 Defence univerisity,Collage of Engineering 11


Example
pi
ans =
3.1416
>> format long
>> pi
ans =
3.141592653589793
>> format short
>> pi
ans =
3.1416

09/13/2021 Defence univerisity,Collage of Engineering 12


some commands used in mat-lab

• clear : clear all removes all variables from the workspace.

• who: who will give more details which include size, space allocation, and class
of the variables.
• clc: To clear the Command Window
• ctrl-c: To abort a MATLAB computation

• . . . : To continue a line

09/13/2021 Defence univerisity,Collage of Engineering 13


some functions used in matlab
The following table lists some commonly used functions, where variables x and y can
be numbers, vectors, or matrices.

Table : Elementary functions

sign(x) Signum function


cos(x) Cosine
max(x) Maximum value
sin(x) Sine
min(x) Minimum value
tan(x) Tangent
ceil(x) Round towards +1
acos(x) Arc cosine
floor(x) Round towards ¡1
asin(x) Arc sine
exp(x) Exponential
atan(x) Arc tangent
angle(x) Phase angle
round(x) Round to nearest integer
log10(x) Common logarithm
sqrt(x) Square root
conj(x) Complex conjugate
rem(x) Remainder after division
exp(x) Exponential
log(x) Natural logarithm
abs(x) Absolute value

09/13/2021 Defence univerisity,Collage of Engineering 14


Predefined constant values used in matlab

09/13/2021 Defence univerisity,Collage of Engineering 15


3. Logical operations
• can deal with logical a expression, that is expressions that are either true or false.
This is achieved by attaching a numerical value to the words ‘true’ and ‘false’; a
value is ‘true’ if and only if it is non-zero.

09/13/2021 Defence univerisity,Collage of Engineering 16


3. Relational and logical operators
A relational operator compares two numbers by determining whether a
comparison is true or false. Relational operators are shown in Table 2.
Operator Description

> Greater than


< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
~= Not equal to
& AND operator
│ OR operator
~ NOT operator

A comparison is true, a Matlab is display 1


09/13/2021 Defence univerisity,Collage of Engineering 17
A comparison is false, a Matlab is display 0
example
u = [1 0 2 4 0 2];
v = [5 6 1 0 0 7]; 4. u == 2
ans = 0 0 1 0 0 1
1. u & v
ans = 1 0 1 0 0 1 5. • Are any of the entries of v
non-zero?
2. u | v
any(v)
ans = 1 1 1 1 0 1
ans = 1
• Are all of the entries of v non-
3. “not u” zero?
~u all(v)
ans = 0 1 0 0 1 0 • ans = 0

09/13/2021 Defence univerisity,Collage of Engineering 18


09/13/2021 Defence univerisity,Collage of Engineering 19
Logical Expressions Using the find Function.

The find function determines the index of array elements that meet a given logical condition. The
function is useful for creating masks and index matrices. In its most general form, find returns a
single vector of indices. This vector can be used to index into arrays of any size or shape.

For example,
A = magic(4)
A=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

i = find(A > 8);


A(i) = 100

A=
100 2 3 100
5 100 100 8
100 7 6 100
09/13/2021 Defence univerisity,Collage of Engineering 20
4 100 100 1
You can also use
Example
Find to obtain both the row and column indices of a rectangular matrix for the array values that meet the
logical condition:
A = magic(4)
A=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
[row, col] = find(A > 12)
Ans
row =
1
4
4
1
col =
1
2
3
4
09/13/2021 Defence univerisity,Collage of Engineering 21
MATRICES

• Matrices are the basic elements of the MATLAB environment.

• A matrix is a two-dimensional array consisting of m rows and n columns.


• Special cases are column vectors (n = 1) and row vectors (m = 1).

• MATLAB supports two types of operations, known as matrix operations and array
operations. Matrix operations will be discussed first.

09/13/2021 Defence univerisity,Collage of Engineering 22


Matrix generation
Matrices are fundamental to MATLAB. Therefore, we need to become familiar
with matrix generation and manipulation. Matrices can be generated in
several ways.
1. Entering a vector

To enter a row vector: The elements of vectors in MATLAB are enclosed by


square brackets and are separated by spaces or by commas.

Example
v = [1 4 7 10 13]

09/13/2021 Defence univerisity,Collage of Engineering 23


2. Column vectors are created in a similar way, however, semicolon (;) must
separate the components of a column vector,
w = [1;4;7;10;13]
• Thus, v(1) is the first element of vector v, v(2) its second element, and so forth.
• Furthermore, to access blocks of elements, we use MATLAB's colon notation
(:).
For example, to access the first three elements of v, we write,
>> v(1:3)
ans =
147
all elements from the third through the last elements,
>> v(3,end)
ans =
7 10 13
>> v(:)
produces a column vector, whereas writing
>> v(1:end)
produces a row vector.
09/13/2021 Defence univerisity,Collage of Engineering 24
Entering a matrix

A matrix is an array of numbers. To type a matrix into MATLAB you must


begin with a square bracket, [
separate elements in a row with spaces or commas (,)
use a semicolon (;) to separate rows
end the matrix with another square bracket, ].
type,
>> A = [1 2 3; 4 5 6; 7 8 9]
MATLAB then displays the 3 x 3 matrix as follows,
A=
1 2 3
4 5 6
7 8 9

09/13/2021 Defence univerisity,Collage of Engineering 25


Cont..

We can view a particular element in a matrix by specifying its location.


We write,

>> A(2,1)
A(2,1) is an element located in the second row and first column. Its value is 4

Correcting any entry is easy through indexing. Here we substitute A(3,3)=9 by


A(3,3)=0. we can write as follow

 
>> A(3,3) = 0

09/13/2021 Defence univerisity,Collage of Engineering 26


Colon operator

Often we must deal with matrices or vectors that are too large to enter one element
at a time. For example, suppose we want to enter a vector x consisting of points
(0, 0.1, 0.2, 0:3,...,5). We can use the command.
 

>> x = 0:0.1:5;
The row vector has 51 elements.

09/13/2021 Defence univerisity,Collage of Engineering 27


Linear spacing

It is similar to the colon operator (:), but gives direct control over the number
of points. For example,

>> y = linspace(a,b,n)
generates a row vector y of n points linearly spaced between and including a
and b

09/13/2021 Defence univerisity,Collage of Engineering 28


Colon operator in a matrix

The colon operator can also be used to pick out a certain row or column. For
example, the statement A(m:n,k:l) specifies rows m to n and column k to
l. Subscript expressions refer to portions of a matrix. For example,
>> A(2,:); is the second row elements of A.

>> A(:,2:3); is a sub-matrix with the last two columns of A.

09/13/2021 Defence univerisity,Collage of Engineering 29


Creating a sub-matrix

>> B = A([2 3],[1 2]); extract a submatrix B consisting of rows 2 and 3 and columns 1

and 2 of the matrix A.

>> C = A([2 1 3],:); interchange rows 1 and 2 of A

It is important to note that the colon operator (:) stands for all columns or all rows.

As a special case, a colon (:) as the row or column speci¯er covers all entries in that

row or column; thus

A(:,j) is the jth column of A, while

A(i,:) is the ith row, and

A(end,:) picks out the last row of A.

09/13/2021 Defence univerisity,Collage of Engineering 30


Transposing a matrix

The transpose operation is denoted by an apostrophe or a single quote ('). It


flips a matrix about its main diagonal and it turns a row vector into a
column vector.
>> A'

09/13/2021 Defence univerisity,Collage of Engineering 31


Matrix generators

MATLAB provides functions that generates elementary


matrices.
 
Table 3

eye(m,n) Returns an m-by-n matrix with 1 on the main diagonal


eye(n) Returns an n-by-n square identity matrix
zeros(m,n) Returns an m-by-n matrix of zeros
ones(m,n) Returns an m-by-n matrix of ones
diag(A) Extracts the diagonal of matrix A
rand(m,n) Returns an m-by-n matrix of random numbers

09/13/2021 Defence univerisity,Collage of Engineering 32


Some Special Vectors and Matrices

09/13/2021 Defence univerisity,Collage of Engineering 33


Matrix Calculations
• Addition

• Multiplication

• Inverse

09/13/2021 Defence univerisity,Collage of Engineering 34


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

b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1

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

09/13/2021 Defence univerisity,Collage of Engineering 35


Solving Simultaneous Equations
Ax=b

• A=matrix of coefficients,
• x = vector of variables,
• b = vector of values.

• In matrix form the above system and its solution can be written as

• In MATLAB we write as x = inv(A)*b

09/13/2021 Defence univerisity,Collage of Engineering 36


Changing Dimensions
In addition to the transpose operator, MATLAB has several built-in functions that change
the dimensions or configuration of matrices, including reshape, fliplr, flipud, and rot90.
The reshape function changes the dimensions of a matrix. The following matrix
variable mat is 3 x 4 or, in other words, it has 12 elements (each in the range from 1 to
100).
mat = randi(100, 3, 4)
14 61 2 94
21 28 75 47
20 20 45 42
The reshape function iterates through the matrix column wise. For example, when
reshaping mat into a 2 x 6 matrix, the values from the first column in the original
matrix (14, 21, and 20) are used first, then the values from the second column (61, 28,
20), and so forth.
>> reshape(mat,2,6)
ans =
14 20 28 2 45 47
21 09/13/2021
61 20 75 94 42 Defence univerisity,Collage of Engineering 37
Cont…
 The ‘ fliplr ‘function “flips” the matrix from left to right (in other words, the left
most column, the first column, becomes the last column and so forth), and
 The flipud function flips up to down.
>> mat
mat =
14 61 2 94
21 28 75 47
20 20 45 42
>> fliplr(mat)
ans =
94 2 61 14
47 75 28 21
42 45 20 20

09/13/2021 Defence univerisity,Collage of Engineering 38


The flipud function flips up to down.
% flipud(mat)
ans =
20 20 45 42
21 28 75 47
14 61 2 94

• The rot90 function rotates the matrix counterclockwise 90 degrees, so, for example, the
value in the top right corner becomes instead the top left corner and the last column
becomes the first row.
mat

>> rot90(mat)
ans =
94 47 42
2 75 45
61 28 20
14 21 20
09/13/2021 Defence univerisity,Collage of Engineering 39
Differentiation:
The MATLAB symbolic toolbox is very useful for checking calculus problems.
For example, to find diff_f = where f = e-axx3bsin(cx) and a, b and c are
unspecified constants, we do the following
syms x
f=exp(-a*x)*a^(3*x)*sin(c*x);
diff_f = diff(f,x)

Notice that the result is quite d f


2

2
complex. To ask MATLAB to try to
dx
simplify it, type:
>> diff_f_simp = simple(diff_f)

For example, to find diff2_f = we do


>> diff2_f=diff(f,x,2)
using the already defined expression for f.

09/13/2021 Defence univerisity,Collage of Engineering 40


Definite integrals:
For the definite integral, int_def_g = enter
>> clear, clc, syms a c x; g = exp(-a*x)*sin(c*x), int_def_g = int(g,x,-pi,pi)
 
When MATLAB is unable to find an analytical (symbolic) integral, such as with
 
>> clear, clc, syms x, int(exp(sin(x)),0,10)

09/13/2021 Defence univerisity,Collage of Engineering 41


Differentiation

• The first step is to tell MATLAB that the variables to be used are symbolic.
This is most easily done using the “syms” command. For example, in the
following we will use x, y, a, b and c as symbolic quantities. So enter:
>> syms x y a b c f g

In the Workspace window (or use >> whos) note that these variables are
symbolic, rather than the usual double precision numeric variables.

09/13/2021 Defence univerisity,Collage of Engineering 42


Indefinite integrals:
Thus, for example, to find the indefinite integral int_g = ,
where g = e-axsin(cx), we do:  
>> clear,
clc,
syms a c x;
g=exp(-a*x)*sin(c*x),
int_g = int(g,x)
>> diff_int = diff(int_g,x)
This should give back g, but it doesn’t look the same because MATLAB doesn’t always
give things in the simplest format. In this case, we again use the simple command.
>> diff_int_simp = simple(diff_int)
For example, try to find (where, as before, f = e-axx3bsin(cx) and a, b and c are
unspecified constants).
>> clear, clc, syms a b c x; f = exp(-a*x)*x^(3*b)*sin(c*x), int(f,x)

09/13/2021 Defence univerisity,Collage of Engineering 43


Integrate Quartic Polynomial

• Evaluate
Matlab program
• Create a vector to represent the polynomial
p = [3 0 -4 10 -25];
q = polyint(p)
p = [3 0 -4 10 -25]; a = -1;
Use polyint to integrate the polynomial using b = 3;
a constant of integration equal to 0.
I = diff(polyval(q,[a b]))
q = polyint(p)
q =   0.6000 0 -1.3333 5.0000
-25.0000 0 
Find the value of the integral, I, by evaluating
q at the limits of integration.
a = -1;
b = 3;
I = diff(polyval(q,[a b]))
Answer I = 49.0667
09/13/2021 Defence univerisity,Collage of Engineering 44
Integrate Product of Two Polynomials

• Create vectors to represent the


Class work polynomials and

Evaluate
p = [1 0 -1 0 0 1];
v = [1 0 1];
k = 3;
q = polyint(conv(p,v),k)
a = 0;
b = 2;
I = diff(polyval(q,[a b]))

09/13/2021 Defence univerisity,Collage of Engineering 45


Solution of equations: The symbolic toolbox in MATLAB is capable of solving
many types of equations, including non-linear ones and several simultaneous
equations. The steps in solving one or more equations using “solve” are:
 
Step 1: Define the variables in the equations as symbolic using the “syms”
command.
Step 2: Define the equations (see the examples below).
Step 3: Solve the equations using the “solve” command.
Step 4: If there is more than one solution, decide which is physically
reasonable and select it.

Step 5: Check the solution by substituting it back into the original


equation(s).

09/13/2021 Defence univerisity,Collage of Engineering 46


Example 1:
Find the two solutions to the classic quadratic equation, ax2 + bx + c = 0. There
are three ways to do this:
 
1:>> clear, clc, syms x a b c; eq = 'a*x^2+b*x+c = 0', [x]=solve(eq,x)
 
Note that single quotation marks must be placed around an equation that is
assigned to a variable, here eq.
 
If you don't specify the right side of the equation, solve assumes that the
expression equals zero. So here we could have used:
 
2: >> clear, clc, syms x a b c; expn = a*x^2 + b*x + c,
[x]=solve(expn, x)
09/13/2021 Defence univerisity,Collage of Engineering 47
Example 2: Find the solution to e2x=3y:
 
>> clear, clc, syms x y; eq = 'exp(2*x) = 3*y', [x] = solve(eq, x)

09/13/2021 Defence univerisity,Collage of Engineering 48


Example 3: Find the solution to the following set of linear equations:
 
2x-3y+4z = 5
y+4z+x = 10
-2z+3x+4y = 0
 
clear, clc, syms x y z;
eq1 = '2*x-3*y+4*z = 5‘
eq2 = 'y+4*z+x = 10‘
eq3 = '-2*z+3*x+4*y = 0'
[x,y,z] = solve(eq1,eq2,eq3,x,y,z)

09/13/2021 Defence univerisity,Collage of Engineering 49


equationsToMatrix
[A,B] = equationsToMatrix([eqn1, eqn2,
if you do not have the system of linear eqn3], [x, y, z])
equations in the form AX = B, use A=
equationsToMatrix to convert the equations [ 2, 1, 1]
into this form. Consider the following [ -1, 1, -1]
system.
[ 1, 2, 3]
2x+y+z=2
−x+y−z=3
B=
1+2y+3z=−10
2
Declare the system of equations.
3
syms x y z
-10
eqn1 = 2*x + y + z == 2;
Use linsolve to solve AX = B for the vector
eqn2 = -x + y - z == 3; of unknowns X.
eqn3 = x + 2*y + 3*z == -10; X = linsolve(A,B)
Use equationsToMatrix to convert the X=
equations into the form AX = B. The
3
second input to equationsToMatrix
specifies the independent variables in the 1
equations. -5
From X, x = 3, y = 1 and z = -5.
09/13/2021 Defence univerisity,Collage of Engineering 50
Reduced row echelon form (Gauss-Jordan elimination)
• Syntax Examples
Use rref on a rank-deficient magic square:
• R = rref(A) A = magic(4),
R = rref(A)
[R,jb] = rref(A)  
[R,jb] = rref(A,tol) A=
16 2 3 13
• Description 5 11 10 8
9 7 6 12
• R = rref(A) produces the reduced row 4 14 15 1
 
echelon form of A using Gauss Jordan
R=
elimination with partial pivoting. A default 1 0 0 1
0 1 0 3
tolerance of
0 0 1 -3
(max(size(A))*eps *norm(A,inf)) tests for 0 0 0 0

negligible
09/13/2021
column elements. Defence univerisity,Collage of Engineering 51
Cont…

Example 4: We can also solve simultaneous non-linear equations, e.g. y = 2e x and y =


3-x2:
 

>> clear, clc, exp1 = 'y - 2*exp(x)'; exp2 = 'y-3+x^2';


>> ezplot(exp1), hold on; ezplot(exp2); hold off

The "hold on" command tells MATLAB to write the following plots on top of the first
one, rather than replacing it. Approximate values of the solutions (intersections) can
be obtained in the Figure window by clicking on Tools / Zoom In, clicking on a
desired intersection to enlarge that area of the graph, clicking on Tools / Data Cursor,
and then clicking on that intersection again to give the approximate values of x and y
there. Compare these results with those found above using the solve command.

09/13/2021 Defence univerisity,Collage of Engineering 52


Cont….
Example 5: There are equations with an infinite number of solutions, for
example sin(x) = 1/2.
• It is helpful to see some of these solutions by plotting y = sin(x)-1/2 and seeing
approximately where it has values of zero:
 
>> clear, clc, exp1='y - sin(x) + 1/2', exp0='0'
>> ezplot(exp1,[-6,6,-2,1]), hold on; ezplot(exp0); hold off
 
• The "hold on" command tells MATLAB to write following plots on top of the
first one, rather than replacing it. Plotting 0 puts a horizontal line on the graph.
Intersections of the sine wave with this line represent solutions of the first
equation. Approximate values can be obtained in the Figure window by
clicking on Tools / Zoom In, clicking on a desired intersection to enlarge that
area of the graph, clicking on Tools / Data Cursor, and then clicking on that
intersection again to give the approximate values of x and y there. Try this on
the first two intersections to the right of the origin (x > 0). Write down your
results to compare with those found below using solve commands.

09/13/2021 Defence univerisity,Collage of Engineering 53


Limits: The symbolic toolbox also contains a command for finding limits of expressions, e.g.:
   sin( ax ) 
lim  
x 0
 x 

>> clear, clc, syms x a; value = limit(sin(a*x)/x,x,0)

There are cases where the limit depends on the direction from which it is approached.
Consider the plot of tan(x) versus x generated by:

>> clear, clc, ezplot('tan(x)')

Suppose we want the value of tan(x) at x = /2. We could use MATLAB's numeric engine as follows:
 
>> tan(pi/2)
 
Does this give a correct result? Recall that tan(/2) can be either + or -, depending on whether we
approach from the left or the right.

We can use the symbolic engine to find the two correct solutions, as follows:
 
>> clear, syms x, tanhalfpiright = limit(tan(x),x,pi/2,'right')
>> 09/13/2021 Defence univerisity,Collage of Engineering
tanhalfpileft = limit(tan(x),x,pi/2,'left') 54
MATLAB M-Files

• For complicated problems, the simple editing


tools provided by the Command Window are
insufficient.
• A much better approach is to create an M-file
which are ordinary text files containing
MATLAB commands with .m extension. There
are two different kinds of M-files: script M-
files and function M-files.

09/13/2021 Defence univerisity,Collage of Engineering 55


• Script M-files
• The simplest MATLAB programs are called scripts which are stored in M-files.
Script M-files execute a series of MATLAB statements without any input and
output arguments.
• Example
NoOfStudents = 6000;
TeachingStaff = 150;
NonTeachingStaff = 20;
Total = NoOfStudents + TeachingStaff ... + NonTeachingStaff;

 After creating and saving the file, you can run it in two ways −
Clicking the Run button on the editor window or Just typing the filename (without
extension) in the command prompt :
The command window prompt displays the result −
6170

09/13/2021 Defence univerisity,Collage of Engineering 56


Example

• Create a script file, and type the following code −

a = 5;

b = 7;
c=a+b

d = c + sin(b)
e=5*d

f = exp(-d)
When the above code is compiled and executed, it produces the following result −
• c = 12 d = 12.657 e = 63.285 f = 3.1852e-06

09/13/2021 Defence univerisity,Collage of Engineering 57


Cont…

• Function M-files

• Function M-files accept input arguments and produce output. Note that it is
appropriate to use inline functions for defining simple functions that can be
expressed in one line. Function M-files are useful for defining functions
that require several commands to compute the output.
 function [output_parameters] = function_name (input_parameter)

09/13/2021 Defence univerisity,Collage of Engineering 58


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
1

0.8

0.6

>>y=sin(x);
0.4

• Plot the y-array 0.2

-0.2

-0.4

-0.6
>>plot(y) -0.8

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

09/13/2021 Defence univerisity,Collage of Engineering 59


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


0.7

>>plot(y2) 0.6

0.5

0.4

0.3

0.2

0.1

-0.1

-0.2

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

09/13/2021 Defence univerisity,Collage of Engineering 60


Display Facilities 0.7

0.6

0.5

• plot(.) 0.4

0.3

Example:
0.2

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

>>y=sin(x); -0.1

>>plot(y) -0.2

>>plot(x,y) -0.3
0 10 20 30 40 50 60 70 80 90 100

0.7

• stem(.) 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

09/13/2021 Defence univerisity,Collage of Engineering 61


Display Facilities
• title(.)
This is the sinus function
>>title(‘This is the sinus function’) 1

0.8

• xlabel(.) 0.6

0.4

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

sin(x)
0

• ylabel(.)
-0.2

-0.4

-0.6

-0.8
>>ylabel(‘sin(x)’) -1
0 10 20 30 40 50 60 70 80 90 100
x (secs)

09/13/2021 Defence univerisity,Collage of Engineering 62


Introduction to graphics
• There are several plot functions in MATLAB beginning with “ez” that plot symbolic
expressions.
• For example, the function ezplot will draw a 2-D plot in the x-range from –2p to 2p,
with the expression as the title (in pretty form).
• For example, to graph x2 + 2x + 1 on the interval −2 to 2 using the string form:
• >> ezplot (x.^2 + 2*x + 1, [-2 2])
• The command plotproduces 2D graphics. Before using plot command, define the
interval for the independent variable xand the function of the form y=f(x).Then plot
(x,y) commandis called to obtain the figure of f(x) with respect to x:
>> x = 0:0.1:2*pi;
>> y = sin(x);
>> plot (x,y)
 
>> x = 1:5;
>> y = [0 -2 4 11 3];
>> z = 2:2:10;
>> plot3(x,y,z,'k*')
09/13/2021 Defence univerisity,Collage of Engineering 63
>> grid
Generating a MATLAB Plot

The basic command to generate a plot window is


plot(x,y)
where x and y are vectors of the same length. In order to put multiple series of data on
the same
plot, include the x-y vector pairs of the additional data in the plot command.
plot(x1,y1,x2,y2,x3,y3)
Multiple data series on the same plot can also be accomplished using the hold
command.
plot(x1,y1); hold on;
plot(x2,y2); hold off;a
Multiple plots can be placed on a single page using the subplot command.
subplot(2,1,1); 2,1 specifies 2×1 plot layout on the page; the last digit,
1, selects the first plot
plot(x1,y1,x2,y2); plots two lines in the first plot
subplot(2,1,2); selects the second plot on the page
plot(x3,y3); plots one line in the second plot
09/13/2021 Defence univerisity,Collage of Engineering 64
table 6: attribute for plot

Symbol Color Symbol Line Style Symbol Marker

K Black - Solid + Plus sign


r Red -- Dashed o Circle
b Blue : Dotted * Asterisk
g Green -. Dash-dot . Point
c Cyan none No line x Cross
m Magenta s Square
y Yellow d Diamond

09/13/2021 Defence univerisity,Collage of Engineering 65


Examples

1. Write a programe to plot sinusoidal

ans
% Plot a sine curve:

x = -pi:.1:pi;

y = sin(x);

plot(x,y)

2. Create line plot using specific line width, marker color, and marker size:
09/13/2021 Defence univerisity,Collage of Engineering 66
Ans
Create line plot using specific line width, marker color, and marker size:
x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)

09/13/2021 Defence univerisity,Collage of Engineering 67


Cont…

Multiple Axis Regions (subplot)

You can display multiple plots in the same Figure window and print them on
the same piece of paper with the Subplot function.

subplot(m,n,i) breaks the Figure window into an m-by-n matrix of small sub-
plots and selects the ith subplot for the current plot. The plots are numbered
along the top row of the Figure window, then the second row, and so forth.

For example, the following statements plot data in four different subregions of
the Figure window.

09/13/2021 Defence univerisity,Collage of Engineering 68


t = 0:pi/20:2*pi;
[x,y] = meshgrid(t);
subplot(2,2,1)
plot(sin(t),cos(t))
axis equal
subplot(2,2,2)
z = sin(x)+cos(y);
plot(t,z)
axis([0 2*pi − 2 2])
subplot(2,2,3)
z = sin(x).*cos(y);
plot(t,z)
axis([0 2*pi − 1 1])
subplot(2,2,4)
z = (sin(x).^2) −(cos(y).^2);
plot(t,z)
axis([0 2*pi −1 1]

09/13/2021 Defence univerisity,Collage of Engineering 69


Bar graphs

1.For a matrix, the bar and barh functions will group together the values in each
row are 1st and 2nd groups are 8 19 43 25; 35 44 30 45 respectively.
For example:
%groupages = [8 19 43 25; 35 44 30 45]
groupages =
8 19 43 25
35 44 30 45
>> bar(groupages)
>> xlabel('Group')
>> ylabel('Ages')

09/13/2021 Defence univerisity,Collage of Engineering 70


pie chart
MATLAB has a function, pie, that will create a pie chart. Calling the function
with the form pie(vec) draws a pie chart using the percentage of each
element of vec of the whole (the sum). It shows these starting from the top
of the circle and going around counterclockwise.
For example, the first value in the vector [11 14 8 3 1] , 11 is 30% of the sum,
14 is 38% of the sum, and so forth, as
shown in Figure
>> pie([11 14 8 3 1])
>> pie([11 14 8 3 1], {'A','B','C','D', 'F'})

09/13/2021 Defence univerisity,Collage of Engineering 71


Graphing equations and functions:
MATLAB’s symbolic engine has commands for plotting symbolic equations and functions,
appropriately starting with “ez.” For two-dimensional graphs, we use “ezplot.” As an
example here we use the equation for a circle of radius 2, x2+y2 = 4.
 
Step 1: Move everything to the left-hand side of the equation, i.e. x2 + y2 – 4 = 0
Step 2: Clear and define x and y as symbolic.
Step 3: Define a variable equal to the left-hand side of the equation, inside single
straight quotation marks.
Step 4: Use ezplot, as follows:
 
>> clear, clc, lhs = 'x^2+y^2 - 4'; ezplot(lhs,[-3,3,-2.5,2.5])

When using Word, to get straight quotation marks click on the File tab, then
Options/Proofing/Auto Format and click off "Straight quotes" with “smart quotes”. Do
the same with Auto Correct Options/ Auto Format As You Type.

09/13/2021 Defence univerisity,Collage of Engineering 72


Three-dimensional plots

Three-dimensional plots can be created using the ezmesh and ezsurf commands. For these commands an explicit form must be
used, i.e. z = f(x,y). It is the f(x,y) that is entered into the command. The code below illustrates some possibilities. The lines
with % are comments and are not executed by MATLAB. Open the excellent MATLAB editor by >> edit, cut and paste the code
below into your editor, save it on your Current Directory as symplot3D.m, make certain the Current Directory is in MATLAB’s
path (File/Set Path).
 
% symplot3D.m
% Some 3d plots, where z = the expressions shown
% In the figure window, click on Tools, Rotate 3D.
% Then put cursor on figure, hold down left mouse,
% move cursor to rotate figure. Notice that this
% gives you a better feeling for its 3D shape.
% Have some fun and create your own shapes.
clear, clc
syms x y
ex1='sqrt(4-x^2-y^2)';
figure(1); ezsurf(ex1,[-2,2,-2,2]);
ex2='x^2-y^2';
figure(2); ezsurf(ex2);
ex3='x^2+2';
figure(3); ezmesh(ex3);
ex4='x + y';
figure(4); ezmesh(ex4);

Select each figure in turn, and in the Figure window Tools / Rotate 3D. Put the cursor anywhere on the figure, hold down the left
mouse09/13/2021
button, and move the mouse to rotate Defence univerisity,Collage of Engineering
the figure. 73
Three-dimensional plots

Three-dimensional plots can be created using the ezmesh and ezsurf commands. For these commands an explicit form must be
used, i.e. z = f(x,y). It is the f(x,y) that is entered into the command. The code below illustrates some possibilities. The lines
with % are comments and are not executed by MATLAB. Open the excellent MATLAB editor by >> edit, cut and paste the code
below into your editor, save it on your Current Directory as symplot3D.m, make certain the Current Directory is in MATLAB’s
path (File/Set Path).
 
% symplot3D.m
% Some 3d plots, where z = the expressions shown
% In the figure window, click on Tools, Rotate 3D.
% Then put cursor on figure, hold down left mouse,
% move cursor to rotate figure. Notice that this
% gives you a better feeling for its 3D shape.
% Have some fun and create your own shapes.
clear, clc
syms x y
ex1='sqrt(4-x^2-y^2)';
figure(1); ezsurf(ex1,[-2,2,-2,2]);
ex2='x^2-y^2';
figure(2); ezsurf(ex2);
ex3='x^2+2';
figure(3); ezmesh(ex3);
ex4='x + y';
figure(4); ezmesh(ex4);

Select each figure in turn, and in the Figure window Tools / Rotate 3D. Put the cursor anywhere on the figure, hold down the left
mouse09/13/2021
button, and move the mouse to rotate Defence univerisity,Collage of Engineering
the figure. 74
Loops

Loops in MATLAB is that allow other statement(s) to be repeated.


The statements that do this are called looping statements, or loops.
There are two basic kinds of loops in programming:
counted loops and conditional loops.
A counted loop is a loop that repeats statements a specified number of times (so,
ahead of time it is known how many times the Statements are to be repeated). In a
counted loop, for example, you might say “repeat these statements 10 times”.
A conditional loop also repeats statements, but ahead of time it is not known how
many times the statements will need to be repeated. With a conditional loop, for
example, you might say “repeat these statements until this condition becomes
false”. The statement(s) that are repeated in any loop are called the action of the
loop.
09/13/2021 Defence univerisity,Collage of Engineering 75
THE FOR LOOP

The for statement, or the for loop, is used when it is necessary to repeat
statement(s) in a script or function, and when it is known ahead of
time how many times the statements will be repeated. The statements
that are repeated are called the action of the loop. For example, it may
be known that the action of the loop will be repeated five times. The
terminology used is that we iterate through the action of the loop five
times.
For example , the variable might iterate through the integers 1 through 5
(e.g., 1, 2, 3, 4, and then 5). Although, in general, variable names
should be mnemonic, it is common in many languages for an iterator
variable to be given the name i (and if more than one iterator variable
is needed, i, j, k, l, etc.).

09/13/2021 Defence univerisity,Collage of Engineering 76


The general form of the for loop is:
Where
for loopvar = range • loopvar is the loop variable,
action • “range” is the range of values
end through which the loop variable is
to iterate, and
• The action of the loop consists of
all statements up to the end. Just
like with if statements, the action is
indented

09/13/2021 Defence univerisity,Collage of Engineering 77


THE PROGRAMMING CONCEPT
The loop could be entered in the Command Window, although, like if
and switch statements, loops will make more sense in scripts and
functions. In the Command Window, the results
would appear after the for loop:

>> for i = 1:5


fprintf('%d\n',i)
end
Ans
1
2
3
4
09/13/2021
5
Defence univerisity,Collage of Engineering 78
Class work
How could you print this column of integers (using the programming
method):
0
50
100
150
200

Answer
In a loop, you could print these values starting at 0, incrementing by 50 and
ending at 200. Each is printed using a field width of 3.
>> for i = 0:50:200
fprintf('%3d\n',i)
end 09/13/2021 Defence univerisity,Collage of Engineering 79
What is the out put?

for i = 1:3
fprintf('I will not chew gum\n')
End

Ans

produces the output:


I will not chew gum
I will not chew gum
I will not chew gum

09/13/2021 Defence univerisity,Collage of Engineering 80


For Loop Example: Subplot

A function that is very useful with all types of plots is subplot, which
creates a matrix of plots in the current Figure Window.
Three arguments are passed to it in the form subplot(r,c,n),
Where
r and c are the dimensions of the matrix and
n is the number of the particular plot within this matrix.
The plots are numbered row wise, starting in the upper left corner. In
many cases, it is useful to create a subplot in a for loop so the loop
variable can iterate through the integers 1 through n.
When the subplot function is called in a loop, the first two arguments will
always be the same as they give the dimensions of the matrix. The third
argument will iterate through the numbers assigned to the elements of
the
matrix.
09/13/2021 Defence univerisity,Collage of Engineering 81
For example
in one Figure Window, between using 20 points and 40 points to plot sin(x)
between 0 and 2 * p. The subplot function creates a 1 x 2 row vector of plots in
the Figure Window, so that the two plots are shown side by side. The loop
variable
Iiterates through the values 1 and then 2.

% Demonstrates subplot using a for loop


for i = 1:2
x = linspace(0,2*pi,20*i);
y = sin(x);
subplot(1,2,i)
plot(x,y,'ko')
xlabel('x')
ylabel('sin(x)')
title('sin plot')
end

09/13/2021 Defence univerisity,Collage of Engineering 82


NESTED FOR LOOPS
The action of a loop can be any valid
statement(s). When the action of a
loop is another loop, this is called a • The first for loop is
nested loop. called the outer loop;
• the second for loop is
The general form of a nested for loop called the inner loop.
is as follows:
for loopvarone = rangeone ) outer loop • The action of the outer
% actionone includes the inner loop loop consists (in part;
for loopvartwo = rangetwo ) inner loop there could be other
actiontwo statements) of the
end entire inner loop.
end

09/13/2021 Defence univerisity,Collage of Engineering 83


As an example,

a nested for loop will be demonstrated in a


script that will print a box of stars (*).
% Prints a box of stars
Variables in the script will specify how
many rows and columns to print. % How many will be specified by two variables

% for the number of rows and columns


For example, if rows has the value 3 and
rows = 3;
columns has the value 5, a 3 x 5 box would
be printed. As lines of output are columns = 5;
controlled by printing the newline
% loop over the rows
character, the basic algorithm is as follows.
For every row of output: for i=1:rows
n print the required number of stars % for every row loop to print *'s and then one \n
n move the cursor down to the next line
for j=1:columns
(print ‘\n’).
fprintf('*')
Ans end
*****
fprintf('\n')
*****
09/13/2021 ***** end
Defence univerisity,Collage of Engineering 84
Class work

Write a matlab program to print a triangle of Ans


stars in the following form:
* % Prints a triangle of stars
** % How many will be specified by a
*** variable
% for the number of rows
Hint for ans rows = 3;
for i=1:rows
In this case, the number of stars to print in % inner loop just iterates to the value of i
each row is the same as the row number for j=1:i
(e.g., one star is printed in row 1, two stars
fprintf('*')
in row 2, and so on). The inner for loop
does not loop to columns, but to the value end
of the row loop variable (so we do not fprintf('\n')
need the variable columns): end

09/13/2021 Defence univerisity,Collage of Engineering 85


Combining Nested for Loops and if Statements

The statements inside of a nested loop can be any valid


statements, including any selection statement. For example,
there could be an if or if-else statement as the action, or part
of the action, in a loop.

WHILE LOOPS
The while statement is used as the conditional loop in MATLAB; it is used to
repeat an action when ahead of time it is not known how many times the action
will be repeated.

The general form of the while statement is:


while condition
action
end
The action, which consists of any number of statement(s), is executed as long
as the condition is true.
09/13/2021 Defence univerisity,Collage of Engineering 86
PROGRAM STRUCTURES (control flow )

If statement
The general form of the if statement is
if expression
statements
elseif expression
statements
else
statements
end
 
For Loop
for I=n:m
statements
end

09/13/2021 Defence univerisity,Collage of Engineering 87


Use a while loop to calculate factorial(10).

%Use a while loop to calculate factorial(10).


n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])

09/13/2021 Defence univerisity,Collage of Engineering 88


Introduction to SIMULINK
Simulink
• Used to model, analyze and simulate dynamic systems using
block diagrams.
• Simulink is a graphical, “drag and drop” environment for
building simple and complex signal and system dynamic
simulations – therefore is easy to use.
• It allows users to concentrate on the structure of the problem,
rather than having to worry about a programming language.
• We simulate a model to study the behavior of a system – need
to verify that our model is correct

09/13/2021 Defence univerisity,Collage of Engineering 90


Launch Simulink

09/13/2021 Defence univerisity,Collage of Engineering 91


Create a new model
Click the new-model icon in
the upper left corner to
start a new Simulink file

Create new model under


file/new/model.

09/13/2021 Defence univerisity,Collage of Engineering 92


Your workspace

09/13/2021 Defence univerisity,Collage of Engineering 93


Simulink- libraries
Sources: blocks that have only output, generators
constant,...
Sinks: blocks that have only input, scope, to worspace..
Continuous; integrator, transfer function..
Discrete: discrete transfer function, unite delay, memory..
Math operations: gain, product, sum, trigonometric
functions..
User defined functions: S-function, S-function builder,..
SimPower system: Electrical blocks – electrical sources,
machines, measurements, ….
09/13/2021 Defence univerisity,Collage of Engineering 94
Libraries ….
95

09/13/2021 Defence univerisity,Collage of Engineering


Creating a model
• Model is created by choosing the blocks from different
libraries, dragging them to model window and linking them.
• The parameters of block (shown on picture, sine wave
parameters), can be reached with double click on the block.

09/13/2021 Defence univerisity,Collage of Engineering 96


Select an input block
• Drag a Sine Wave block from the
Sources library to the model
window

09/13/2021 Defence univerisity,Collage of Engineering 97


Select an operator block

09/13/2021 Defence univerisity,Collage of Engineering 98


Select an output block
• Drag a Scope block from the Sinks library to the model
window

09/13/2021 Defence univerisity,Collage of Engineering 99


Connect blocks with signals
• Place your cursor on the
output port (>) of the Sine
Wave block
• Drag from the Sine Wave
output to the Integrator
input
• Drag from the Integrator
output to the Scope input
• Arrows indicate the
direction of the signal flow

09/13/2021 Defence univerisity,Collage of Engineering 100


Set block parameters
• The parameters of block (shown on picture, sine wave and
integrator parameters), can be reached with double click
on the block

09/13/2021 Defence univerisity,Collage of Engineering 101


Configuration parameters
• Numerical solver method, start time, stop
time (it can be also set directly)...

09/13/2021 Defence univerisity,Collage of Engineering 102


Run the simulation
• In the model window, from the Simulation pull-down menu,
select Start

09/13/2021 Defence univerisity,Collage of Engineering 103


Simulation results
• Double-click on the Scope to view the simulation results

09/13/2021 Defence univerisity,Collage of Engineering 104


Summary 105

Type the following at the Matlab command


prompt
>> simulink
The Simulink library should appear
Click File-New to create a new workspace,
and drag and drop objects from the
library onto the workspace.
Selecting Simulation-Start from the pull
down menu will run the dynamic
simulation. Click on the blocks to view
the data or alter the run-time
parameters

09/13/2021 Defence univerisity,Collage of Engineering


09/13/2021 Defence univerisity,Collage of Engineering 106
09/13/2021 Defence univerisity,Collage of Engineering 107
09/13/2021 Defence univerisity,Collage of Engineering 108
09/13/2021 Defence univerisity,Collage of Engineering 109
09/13/2021 Defence univerisity,Collage of Engineering 110
09/13/2021 Defence univerisity,Collage of Engineering 111
09/13/2021 Defence univerisity,Collage of Engineering 112
09/13/2021 Defence univerisity,Collage of Engineering 113
09/13/2021 Defence univerisity,Collage of Engineering 114
09/13/2021 Defence univerisity,Collage of Engineering 115
09/13/2021 Defence univerisity,Collage of Engineering 116
09/13/2021 Defence univerisity,Collage of Engineering 117
09/13/2021 Defence univerisity,Collage of Engineering 118
09/13/2021 Defence univerisity,Collage of Engineering 119
Thanks

Questions ??

09/13/2021 Defence univerisity,Collage of Engineering 120

You might also like