Electerical Programming
Electerical Programming
Electrical
Programming
POW 101
2016
Electrical Programming - MATLAB
Course Contents
Page 2
Electrical Programming - MATLAB
References ………………………………………………….…………………..
Page 3
Electrical Programming - MATLAB
Chapter (1)
Introduction to
MATLAB
Page 4
Electrical Programming - MATLAB
Chapter (1)
Introduction to MATLAB
MATLAB is a programming language developed by The Math Works.
Initially, it was simply a MATrix LABoratory. So, it started out as a matrix
programming language where linear algebra programming becomes simple
and easy when MATLAB is used. It can be run as an interactive software
package to perform numerical calculations on vectors and matrices.
However, today it is much more powerful to be run both under interactive
sessions as well as a batch job program.
Page 5
Electrical Programming - MATLAB
• Engineers usually prefer to deal with graphs rather than numbers, so,
the second step is to introduce MATLAB as a plotting utility that
helps in plotting either two or three-dimensional graphics.
Page 6
Electrical Programming - MATLAB
So, one can say that the calculations are done one line at a time at the
command line using the same syntax as would be used in a file.
Moreover, it is possible to write loops and branches at the command line
if it is needed.
When MATLAB is started, the command prompt (>>) appears on the top
of the screen, which means that MATLAB is ready to accept a command
or a statement on the command line as displayed in the Fig. (1.1).
Page 7
Electrical Programming - MATLAB
• To prevent the result from printing out in the command window, use a
semicolon ( ; ) at the end of the statement. The result will be stored in
memory. Any variable can then be accessed by calling its name.
• The command line can also be used to call any function in a defined path.
To call a function, use the following general syntax :
MATLAB will look for a file called function_name.m and execute all of
the code inside it until it either encounters an error or finishes the file.
If there is an error, an annoying noise will be heard in addition to getting
an error message in red.
In case of finishing the file, MATLAB will relinquish control to the user
by displaying the command prompt ( >> ) at the bottom of the workspace
which means that the MATLAB is ready to accept a new command or
statement.
• Make sure that the used variable’s names are different from the names of
the functions in order to avoid the MATLAB malfunctioning.
Page 8
Electrical Programming - MATLAB
changed by either using the toolbar at the left-hand side of the screen, or
entering the path in the bar at the top.
The current directory is the directory MATLAB will look in first for a
function to be called. Therefore, if you have multiple folders and each of
them has an M-file of the same name, there will not be a discrepancy if
you set the current directory beforehand. The current directory is also the
directory in which MATLAB will first look for a data file.
If you still want to call a function but it is not part of the current directory,
you must define it using MATLAB's pathtool utility as indicated in
Fig (1.3).
Page 9
Electrical Programming - MATLAB
addpath c:\matlab\work
Page 10
Electrical Programming - MATLAB
Page 11
Electrical Programming - MATLAB
Moreover, there are many ways to load files into the workspace. One way
is to use the file menu. To open an m-file click open, whereas to import
data from a data file select import data ... and follow the wizard's
instructions.
Page 12
Electrical Programming - MATLAB
Page 13
Electrical Programming - MATLAB
• When you declare an m-file function, the m-file must be the same
name as the function or MATLAB will not be able to run it. For
example, if you declare a function called factorial :
function Y = factorial(X)
An M-file can be either a function with input and output variables or a list
of commands that represent a program code to be called and executed.
MATLAB requires that the M-file must be stored either in the working
directory or in a directory that is specified in the MATLAB path list.
MATLAB M-files are most efficient when written in a way that utilizes
matrix or vector operations. Loops and If-statements are available, but
should be used sparingly since they are computationally inefficient. There
are two main types of m-files namely:
the variables of the base workspace. This can get very messy and lead to
all sorts of strange errors when loops are involved and the loop variables
are not named properly.
Any command valid at the command line is valid in any m-file as long as
the necessary variables are present in the m-files operating workspace. To
create a script m-file use the following steps:
From Home
Select New
Click on script from the pull-down menu.
Once you are done with typing, use the following steps to save the file:
Click on Save.
Make sure that your file is saved in the directory that is in MATLAB’s
search path. If you have at least two files with duplicated names, then the
one that occurs first in MATLAB’s search path will be executed.
Page 15
Electrical Programming - MATLAB
Or Click on Open
Select Open
Choose the file from the displayed list in the
dialogue box.
10π] while the array (y) holds the values of the function y =
sin(x)/x at these points. Note use of the dot operator (.) before the
3. The command plot creates the graph of the function using the
points generated in the two previous lines..
Page 16
Electrical Programming - MATLAB
fun_name.m.
Page 17
Electrical Programming - MATLAB
Calling the function from the command line or another m-file is done by
invoking the m-file name of the function with the necessary input and
output arguments.
Within the function itself, there must be a statement that defines each of
the output arguments out1, out2, … etc.
Without some declaration the variable for the output argument doesn’t
exist in the function’s workspace. It is good practice to initialize the
output arguments are the beginning of the function.
1.3.4. Path
In order to invoke a function, the m-file containing that function must be
in the current path. There is a default path that can be setup through the
File menu or the (add path) command. The order of the path is
important as MATLAB searches the path in sequence and stops searching
after it find the 1st instance of that m-file name.
• The current directory which can be seen at the top of the MATLAB
window or by typing pwd at the command prompt.
Page 18
Electrical Programming - MATLAB
>> pwd
ans =
C:\Users\Documents\MATLAB
• This is the default path, note that MATLAB will always search the
current directory before searching any of the rest of the path.
Page 19
Electrical Programming - MATLAB
1.4.2. Comments
Placing comments in the code can help the programmer and other people
to understand the code as it gets more complex.
syms x y z; % syms command makes x y and z symbolic
w = [ x y z];
e = [1 2 3];
t = jacobian(e,w);
Comments can also identify who wrote the code and when they wrote it.
% Some code writer
% mm / dd / yyyy
Comment lines begin with the character %, and anything after such a
symbol is ignored by the interpreter. The % character itself only tells the
interpreter to ignore the remainder of the same line. In the MATLAB
Page 20
Electrical Programming - MATLAB
There are two useful keyboard shortcuts for adding and removing chunks
of comments. Select the code you wish to comment or uncomment, and
then press Ctrl-R to place one % symbol at the beginning of each line
Comments are useful for explaining what function a certain piece of code
performs especially if the code relies on implicit or subtle assumptions or
otherwise perform subtle actions. Doing this is a good idea for both the
programmer himself and others who try to read the code. For example :
Page 21
Electrical Programming - MATLAB
Example :
% test.m
% let's ask a user for x
x = input('Please enter a value for x : ')
Page 22
Electrical Programming - MATLAB
>> save file_name X saves only the variable X in binary to the file
named file_name.mat
Page 23
Electrical Programming - MATLAB
from a file. The following are the different syntaxes of the load
command :
>> load file_name loads all the variables from the binary
file named file_name.mat.
Page 24
Electrical Programming - MATLAB
Chapter (2)
Mathematical
Manipulation
Page 25
Electrical Programming - MATLAB
Chapter (2)
Mathematical Manipulation
2.1. Data Types and Operations on Point Values
2.1.1. Boolean and Rational Data and Operators
A large number of MATLAB's built-in functions are operating on two
types of data numbers:
Rational data numbers: these data numbers are the numbers used in
our life and known as decimal numbers such as 1 , 3, - 4.5 , … … etc .
Page 26
Electrical Programming - MATLAB
Addition + a=4+7
Multiplication * c = 5 * 3.5
Division / d=a/b
Exponentiation ^ e=a^b
Array multiply .*
Array power .^
All of these functions except for the modulus work for complex numbers
as well.
Page 27
Electrical Programming - MATLAB
Page 28
Electrical Programming - MATLAB
2.1.2. Strings
Besides data numbers, MATLAB can also manipulate data strings. They
should be enclosed in single quotes, ' … string … ' , for example :
hello world
MATLAB doesn't put the space in between the two strings. If you
want one there you must put it in yourself.
Note : MATLAB strings are case sensitive so that 'a' and 'A' are not
the same.
Page 29
Electrical Programming - MATLAB
>> comNum = 1 + j
>> (-3)^0.25
Page 30
Electrical Programming - MATLAB
Page 31
Electrical Programming - MATLAB
>> imag(A)
ans = 1 0
ans = 45 0
Page 32
Electrical Programming - MATLAB
column =
1
matrix =
1 2 3
4 5 6
Page 33
Electrical Programming - MATLAB
In MATLAB the term array or matrix requires all its rows and all its
columns to be the same size, if a matrix is entered in a wrong format, an
error message will appear as follows :
>> matrix = [1 , 2 , 3 ; 4 , 5]
The number of rows and columns of a matrix can be known through the
built-in (size) function. Following the standard mathematical convention,
the first number is the number of rows and the second is the number of
columns : >> matrix = [1 , 2 , 3 ; 4 , 5 , 6];
>> size(matrix)
ans = 2 3
Page 34
Electrical Programming - MATLAB
Array assignment
The array assignment is done through the equal symbol :
>> a = [1 , 2 , 3]
>> a = [1 , 2 , 3];
Page 35
Electrical Programming - MATLAB
where (i) is the index in the row, and (j) in the column.
>> a = [1 , 2 , 3 ; 4 , 5 , 6];
>> a(1,:) %row 1, every column
ans =
1 2 3
• To access only the first two elements in the first row, the following
syntax may be used :
>> a = [1 , 2 , 3 ; 4 , 5 , 6];
>> a(1, 1:2)
ans = 1 2
Page 36
Electrical Programming - MATLAB
>> 2 * [1 2 3]
ans =
[2 4 6]
Page 37
Electrical Programming - MATLAB
Multiplication and division are more problematic. Using the symbol (*),
MATLAB will compute the matrix product, which is only defined when
the number of columns of the left operand matches the number of rows of
the right operand.
For examples:
>> a = [1 , 2 ; 3 , 4];
>> a * a
ans = 7 10
15 22
>> a = [1 2 3];
>> b = [1 ; 2 ; 3];
>> a * a
??? Error using ==> * inner matrix dimensions must agree.
>> a * b
ans = 14
Using the division symbol ( / ) has even more constraints, as it imposes
the right operand to be invertible. For square matrices:
a/b is equivalent to a * b –1
For example:
>> a = [1 2 ; 3 4];
>> b = [1 2 ; 1 2];
>> b / a
ans =
1 0
1 0
>> a / b
Page 38
Electrical Programming - MATLAB
The other two component wise operators are ( ./ ) and ( .^ ) where the
elements of a matrix can be divided on a component-wise or raised to the
same power.
Page 39
Electrical Programming - MATLAB
Declaring a vector
Vectors are declared as if they were normal arrays, except that they have
one dimension one must have the length of 1. It does not matter if the
array is vertical or horizontal. For instance, both of the following are
vectors:
>> H = [ 1 , 2 , 3];
>> V = [ 4 ; 5 ; 6];
>> isvector(H)
ans = 1
>> isvector(V)
ans = 1
Page 40
Electrical Programming - MATLAB
>> A = [1 2 3 ; 4 5 6];
>> V = A(1 , :)
V=1 2 3
This is a useful way to store multiple vectors and then extract them when
it is need to use them.
Columns 10 through 18
1.9000 2.0000 2.1000 2.2000 2.3000
2.4000 2.5000 2.6000 2.7000
Columns 19 through 21
2.8000 2.9000 3.0000
Note : the linspace function produces a row vector, not a column vector,
to get a column vector use the transpose operator ( ' ) on
Lin_Vector.
• The third argument to the function is the total size of the needed vector,
which will include the first two arguments as endpoints and (n – 2)
Page 41
Electrical Programming - MATLAB
Page 42
Electrical Programming - MATLAB
>> V = [ 4 ; 5 ; 6];
DP = 32
The dot product produces a scalar value, which can be used to find the
angle if used in combination with the magnitudes of the two vectors as
follows:
>> theta = acos(DP/(mag_H*mag_V));
>> theta = 0.2257
The cross product is a vector. Analogous to the dot product, the angle
between two vectors can also be found using the cross product's
magnitude:
Page 43
Electrical Programming - MATLAB
The cross product itself is always perpendicular to both of the two initial
vectors. If the cross product is zero then the two original vectors were
parallel to each other.
eye - function
This function is a tool for creating an identity matrix with 1's on the
diagonal and zeros elsewhere :
>> eye(n) - is the (n-by-n) identity matrix.
>> eye(m,n) - is an (m-by-n) matrix with 1's on
the diagonal and zeros elsewhere.
>> eye(3)
ans = 1 0 0
0 1 0
0 0 1
>> eye(4 , 5)
ans = 1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Page 44
Electrical Programming - MATLAB
ones - function :
This function is a tool for creating a matrix with all elements as 1's :
>> ones(n) - is the (n-by-n) matrix of ones.
>> ones(m,n) - is an (m-by-n) matrix with ones.
>> ones(3)
ans = 1 1 1
1 1 1
1 1 1
>> ones(4 , 5)
ans =
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
zeros - function :
This function is a tool for creating a matrix with all elements as zeros :
>> zeros(n) - is the (n-by-n) matrix of zeros.
>> zeros(m,n) - is an (m-by-n) matrix with zeros.
>> zeros(3)
Page 45
Electrical Programming - MATLAB
ans = 0 0 0
0 0 0
0 0 0
>> zeros(4 , 5)
ans =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
diag – function :
This function is a tool for creating diagonal matrices and getting the
diagonals of a matrix :
>> V = [ 2 3 4 5 6 ];
>> diag(V,2)
Page 46
Electrical Programming - MATLAB
ans = 0 0 2 0 0 0 0
0 0 0 3 0 0 0
0 0 0 0 4 0 0
0 0 0 0 0 5 0
0 0 0 0 0 0 6
0 0 0 0 0 0 0
0 0 0 0 0 0 0
>> diag(A,3)
Page 47
Electrical Programming - MATLAB
>> diag(A,2)
ans = 18
>> diag(A,1)
ans =
25
>> diag(A)
ans = 11.0000
5.0000
1.5000
>> diag(diag(A))
ans =
11.0000 0 0
0 5.0000 0
0 0 1.5000
det – function :
This function is a tool for calculating the determinant of a square matrix :
>> det(A)
ans = 680.9000
Page 48
Electrical Programming - MATLAB
poly – function :
This function is a tool for calculating the characteristic polynomial of a
square matrix:
>> poly(A)
ans =
26.0447
-4.2723 + 2.8090i
-4.2723 - 2.8090i
polyval – function :
This function is a tool for evaluating a polynomial at a given value of the
independent variable.
>> polyval(P , x) where P is a polynomial and x is the parameter
to evaluate the polynomial at its value.
Page 49
Electrical Programming - MATLAB
conv( a , b ) :
This convolution function multiplies two polynomials a and b.
Ex : If p1 = x5 – 3 x4 + 5 x2 + 7 x + 9
p2 = 2 x6 – 8 x4 + 4 x2 + 10 x + 12
P2 = [ 2 0 -8 0 4 10 12]; % P2 coefficients
deconv( a , b ) :
This de-convolution function divides polynomial a by polynomial b and
Ex : If p1 = 2 x6 – 8 x4 + 4 x2 + 10 x + 12
p2 = x5 – 3 x4 + 5 x2 + 7 x + 9
P1 = [ 2 0 -8 0 4 10 12]; % P1 coefficients
P2 = [ 1 -3 0 5 7 9]; % P2 coefficients
[q , r] = deconv( p1 , p2)
Page 50
Electrical Programming - MATLAB
polyder( a ) :
This function produces the coefficients of the derivative of a polynomial
a.
Ex : if p1 = 2 x6 – 8 x4 + 4 x2 + 10 x + 12
a = [ 2 0 -8 0 4 10 12]; % P1 coefficients
der_P1 = polyder( a )
Page 51
Electrical Programming - MATLAB
Chapter (3)
Page 52
Electrical Programming - MATLAB
Chapter (3)
3.1.1. IF statement
An if-statement can be used to execute code once when a logical test
Page 53
Electrical Programming - MATLAB
if expression
…………
………… statements
…………
end
This syntax will evaluate the expression first, and then, if the
evaluation yields logical true or a nonzero result, one or more
MATLAB commands denoted here as statements will be executed.
The expression is usually consisting of variables or smaller
expressions joined by relational operators, or logical functions.
Example (1):
clear
clc
if ( a > b )
end
if ( b > a )
end
Page 54
Electrical Programming - MATLAB
• The if-statement can be used alone or with the else and elseif-
statements. When using elseif and/or else within an if-
statement, the general form of the statement will be :
if expression
…………
… … … … statements
…………
elseif expression2
…………
… … … … statements
…………
else expression3
…………
… … … … statements
…………
end
Example (2):
It is required to create an M-file to be used with MATLAB to solve the
general form of the quadratic equation:
A x2 + b x + c = 0
The program should:
Page 55
Electrical Programming - MATLAB
Quad_eqn.m
% This program has been designed to solve any quadratic
% equation in the form : a . (x^2) + b . (x) + c = 0 then
% displaying its roots and their type using IF-statement.
%
% The coefficients of the equation are entered from the
% keyboard interactively.
clear
clc
Page 56
Electrical Programming - MATLAB
Example (3):
It is required to create an M-file to be used with MATLAB to check for
the divisibility of a given number by 2 or by 3 :
clear
clc
number = input('Give an integer: ' );
remainder2 = rem(number,2);
remainder3 = rem(number,3);
if (remainder2 == 0 & remainder3 == 0 )
disp('Your number is divisible by both 2 and 3')
elseif remainder2 == 0
disp('Your number is divisble by 2 but not by 3')
elseif remainder3 == 0
disp('Your number is divisible by 3 but not by 2')
else
disp('Your number is not divisible by either 2 or 3')
end
switch variable
case value1
…………
………… statements
…………
case value2
…………
………… statements
…………
case value3
…………
………… statements
…………
otherwise
…………
………… statements
…………
end
• The end is only necessary after the entire switch block, not after
each case.
Page 58
Electrical Programming - MATLAB
Example (4):
Quad_eqn_switch.m
% This program has been designed to solve any quadratic
% equation in the form : a . (x^2) + b . (x) + c = 0 then
% displaying its roots and their type using Switch-statement.
% The coefficients of the equation are entered from the
% keyboard interactively.
Clear , clc
a = input(' Enter the coefficient (a) of x^2 : ' ); disp(' ')
b = input(' Enter the coefficient (b) of x : ' ); disp(' ')
c = input(' Enter the absolute coefficient (c) :' ); disp(' ')
d = b^2 - 4*a*c;
j = sqrt(-1);
switch d
disp(' Your equation has the following form : ' ),disp(' ')
disp(sprintf(' %5.2f x^2 + %5.2f x + %5.2f = 0 \n\n ', a, b, c))
case d == 0
x = -b / (2*a);
disp(' This equation has two equal real roots as : ' ), disp(' ')
disp(sprintf(' x1 = %5.2f \n ',x))
disp(sprintf(' x2 = %5.2f ',x))
case d > 0
x1 = (-b + sqrt(d))/(2*a);
x2 = (-b - sqrt(d))/(2*a);
disp(' This equation has two distinct real roots as : ' ), disp(' ')
disp(sprintf(' x1 = %5.2f \n ',x1))
disp(sprintf(' x2 = %5.2f ',x2))
otherwise
x1r = -b/(2*a);
x1i = sqrt(-d)/(2*a);
disp(' This equation has two complex conjugate roots as : ')
disp(' '),disp(sprintf(' x1 = %5.2f + j* %5.2f \n ',x1r,x1i))
disp(sprintf(' x2 = %5.2f - j* %5.2f ',x1r,x1i))
end
Page 59
Electrical Programming - MATLAB
block and executes the error handling code in that block rather than
simply reporting an error to the screen and terminating the entire
program. This is useful for debugging and also for filtering out
calculations causing errors, like accidentally trying to find the inverse of a
singular matrix, and not wishing to end the program entirely. The general
syntax is :
try
…… ……
…… …… statements
…… ……
catch
…… ……
…… …… statements
…… ……
end
Note : The try/catch-block does not rely on any conditions like the
other control flow statements. Therefore the code in the try-block will
always be at least partially executed. Not all of the try-block code will
Page 60
Electrical Programming - MATLAB
…………
………… statements
…………
end
The iterator variable is initialized to start value and is increased by the
amount in increment every time it goes through the loop, until it reaches
the value end value. If the increment is omitted, it is assumed to be 1, as
in the following code:
for ii = 1 : 3
…………
………… statements
…………
end
This would execute statements three times.
Example (5):
Calculate the factorial of a number starting from 1! and going to 10! using
the for-loop.
----------------------- Solution -----------------------
Page 61
Electrical Programming - MATLAB
Page 62
Electrical Programming - MATLAB
Example (6):
Use the Newton’s method to locate the root of the equation :
x3 – 5 x + 3 = 0 near the point x = -3
Taking into account that the Newton’s search method is expressed as :
x i+1 = x i – f(x i ) / f ’(x i )
----------------------- Solution -----------------------
Applying the Newton’s search algorithm considering the initial guess as
x = -3 using the for-loop and repeating the search until the difference
between two successive values of the root (x) becomes equals 0.0001 or
less. This can be carried out using the following m-file :
Page 63
Electrical Programming - MATLAB
…………
………… statements
…………
end
Page 64
Electrical Programming - MATLAB
Page 65
Electrical Programming - MATLAB
Example (8):
Apply the Newton’s method to locate the root of the equation :
x3 – 5 x + 3 = 0 near the point x = -3 using while-loop.
----------------------- Solution -----------------------
clear
clc
% Newton loop :
% -----------
while ( abs(dx) > 0.0001 & counter < 20 )
fx = x^3 - 5*x + 3;
dfx = 3*x^2 -5;
dx = fx / dfx;
x = x - dx;
disp(sprintf(' \n\n The final value of the root (x) = %f ' , x))
Page 66
Electrical Programming - MATLAB
tighter loop control. The break keyword will cause the program to leave
the loop currently in use and continue from the next line after the loop
ends, regardless of the loop's controlling conditions.
If the code is in a nested loop it only breaks from the loop it's in, not all of
them. The syntax is simply to write the word break within the loop
where you desire it to break.
Page 67
Electrical Programming - MATLAB
• Determinant
Getting the determinant of a matrix, requires that the matrix is firstly
defined, then the function det( ) can be run on that matrix, as
follows:
a = [1 2 ; 3 4];
det(a)
ans = -2
• Transpose
To find the transpose of a matrix the apostrophe is placed after the
bracket containing the elements of the matrix. Transpose will switch
the rows and columns of a matrix.
a=[1 2 3]
Page 68
Electrical Programming - MATLAB
b = inv(a);
• The Jacobian
t = jacobian(e,w);
e is a scalar vector
w is a vector of functions.
Also, this does not solve equations symbolically unless you define the
w vector functions as symbolic prior to executing this statement. For
example :
syms x y z;
w=[x y z];
e=[1 2 3];
t=jacobian(e,w);
Page 69
Electrical Programming - MATLAB
R1 = 1 Ω R2 = 2 Ω R3 = 3 Ω Rs
i
+ +
+ R4 = 6 Ω R6 = 2 Ω + Rp
Vs Vo Vs Vo
- -
R5 = 3 Ω
- -
The goal is to determine the value of the input voltage V s required to cause
the current i to be 1 A. Resistors R 1 , R 2 , and R 3 are connected in series and
can be replaced by an equivalent resistor R s given by : Rs = R 1 + R 2 + R 3
while resistors R 4 , R 5 , and R 6 are connected in parallel and can be replaced
by an equivalent resistor R P given by : R p = 1 / (1/R 4 + 1/R 5 + 1/R 6 ) as
shown in Fig (b). Applying voltage division to the circuit in Fig(b) gives :
𝑅𝑅𝑝𝑝
𝑉𝑉𝑜𝑜 = . 𝑉𝑉𝑠𝑠 , where V o is the voltage across R P and is also the voltage
𝑅𝑅𝑠𝑠 + 𝑅𝑅𝑝𝑝
across the parallel resistors in Fig(a). Ohm's law indicates that the current in
R 6 is given by : I = V o /R 6
Page 70
Electrical Programming - MATLAB
Page 71
Electrical Programming - MATLAB
Page 72
Electrical Programming - MATLAB
The current (i) in the resistor R is equal to the mesh current in the third
mesh, that is : i = i3 and the mesh equations can be written using
matrices such as :
clear
clc
% Enter the resistor of the branch of the circuit :
R = input('Enter the value of the branch resistance : ')
% The mesh equations of the circuit :
Z = [ 28 -10 -8 ; -10 28 -8 ; -8 -8 16+R];
V = [ 12 ; 12 ; 0 ];
% Calculate the mesh currents :
Im = Z\V;
% The branch current to be calculated :
I = Im(3)
Page 73
Electrical Programming - MATLAB
The input to this circuit, v s (t), is a sinusoidal voltage. At steady state, the
output, v o (t), will also be a sinusoidal voltage as shown in Fig (a). This
circuit can be represented using phasors and impedances as shown in Fig
(b). Analysis of this circuit proceeds as follows. Let Z 1 denote the
impedance of the series combination of R 1 and jω L, i.e : Z 1 = R 1 + j ω L
Next, let Y 2 denote the admittance of the parallel combination of R 2 and
1/jω C, i.e : Y 2 = 1/R 2 + j ωC and Z 2 = 1/Y 2
Page 74
Electrical Programming - MATLAB
Page 75
Electrical Programming - MATLAB
end
plot (t, vs, t, vo)
The values of both V s and V o are calculated and used to determine the
magnitude and phase angle of the sinusoidal output voltage as displayed in
the following figure.
Page 76
Electrical Programming - MATLAB
Chapter (4)
Page 77
Electrical Programming - MATLAB
Chapter (4)
Page 78
Electrical Programming - MATLAB
First, generate n data points on the curve by creating the following m-file:
n = 100;
x = 2*pi*(0 : n-1) / (n-1);
y1 = sin(x);
y2 = exp(cos(x));
xx = 8*(0 : n-1) / (n-1);
y3 = sin(cos(xx.^2 - xx ));
plot(x, y1)
pause
plot(x, y2)
pause
plot(xx, y3)
y3 = sin(cos(x2 - x))
Page 79
Electrical Programming - MATLAB
Note that the axes are changed for every plot so that the curve just fits
inside the axes.
The x coordinates of the data points can be generated more easily using
the linspace-function as follows :
x = linspace(0, 2*pi, n);
xx = linspace(0, 8, n);
• The endpoints of the axis and the number of points are entered
directly as :
x = linspace(first point, last point, number of points)
Page 80
Electrical Programming - MATLAB
Page 81
Electrical Programming - MATLAB
where ' -- ' means a dashed line and ' : ' means a dotted line.
Page 82
Electrical Programming - MATLAB
The following strings are used to modify the color of the line, to put
markers at the nodes, and to modify the type of line as shown in the tables
below.
Page 83
Electrical Programming - MATLAB
For example,
plot(x, y1, 'r', x, y2, 'g--o', x, y3, 'mp')
• The third has magenta pentagrams at the data points but no line
connecting the points.
We can also plot the first curve, and then add the second, and then the
third by :
plot(x, y1)
Page 85
Electrical Programming - MATLAB
hold on
plot(x, y2)
plot(xx, y3)
hold off
Page 86
Electrical Programming - MATLAB
Note that the axes can change for every new curve; however, all the
curves appear on the same plot.
Instead of putting a number of curves on one plot, the curves can be set
individually in the graphics window. This can be done using the subplot
function to divide the graphics window vertically or horizontally. The
syntax for displaying (m) plots vertically and (n) plots horizontally in
one graphics window is :
subplot(m, n, p)
This divides the graphics window into (m x n) rectangles and selects the
(pth) rectangle for the current plot. All the graphics commands work as
before, but now apply only to this particular rectangle in the graphics
window. One can bounce between these different rectangles by calling
subplot repeatedly for different values of (p).
Page 87
Electrical Programming - MATLAB
• Also, one can force the two axes to have the same scale by :
axis equal or axis image
• The command axis is generally only in effect for one plot. Every new
plot turns it off, so it must be called for every plot unless hold is on.
Page 88
Electrical Programming - MATLAB
semilogx(x,y)
(y). semilogx(x,y)
loglogx(x,y)
Page 89
Electrical Programming - MATLAB
• Since it is often needed to label the axes and put a title on the plot,
there are specific commands for each of these. The syntax of such
commands are :
xlabel(<string>)
ylabel(<string>)
title(<string>)
This will put labels on the x-axis, on the y-axis, and a title on top of
the plot, respectively. Note that a title can contain more than one
line. For example :
plot(x,y3)
xlabel( ‘ X (rad.)’ )
ylabel( ‘ Y3 ‘ )
Page 90
Electrical Programming - MATLAB
Page 91
Electrical Programming - MATLAB
Page 92
Electrical Programming - MATLAB
• <limits> : are the axes limits which represent either [x min x max ] in
case the y-axis just encloses the curve or [x min x max y min y max ] in case
of specifying the endpoints on the y-axis.
• The calculated data points for the function can also be stored by :
[x , y] = fplot(<function name> , <limits>)
Example :
Page 93
Electrical Programming - MATLAB
xlabel( ‘ X- range ’ )
ylabel( ‘ Y = F(x) ‘ )
legend( ‘ F1(x) ‘ , ‘ F2(x) ‘ )
hold off
For example :
f = @(x, y) (x^2 + y^2)^2 - (x^2 – y^2);
ezplot(f)
will plot the Lemniscates of Bernoulli curve, basically an ∞ range
will be considered.
ezplot(f)
Page 95
Electrical Programming - MATLAB
real part of log(x) while ezplot only plots the function for x =
(0, 2π).
The vertical axes are different and ezplot is missing part of the curve.
Page 96
Electrical Programming - MATLAB
hist(x)
• This command will draw ten bins between the minimum and
maximum values of the elements in (x).
hist(x, 50)
Page 97
Electrical Programming - MATLAB
Page 98
Electrical Programming - MATLAB
t = 0 : 0.01 : 2*pi;
polar(t, sin(2*t).^2 , ‘ r ’)
Polar plots can also be generated by the polar command. There is also an
easy command for generating polar plots, namely ezpolar. The syntax
for such command can be written as follows :
Page 99
Electrical Programming - MATLAB
• ezpolar(fun)
• ezpolar(fun, [a,b])
For examples :
ezpolar('sin(2*t).*cos(3*t)')
Page 100
Electrical Programming - MATLAB
ezpolar('sin(2*t).*cos(3*t)',[0 pi/2])
Page 101
Electrical Programming - MATLAB
Chapter (5)
MATLAB SIMULINK
Toolbox
Page 102
Electrical Programming - MATLAB
Chapter (5)
MATLAB SIMULINK Toolbox
Simulink Simulation and Link is an extension of MATLAB. It works
with MATLAB to offer modeling, simulation, and analysis of dynamical
systems under a graphical user interface GUI environment. The
construction of a model is simplified with click and drag mouse
operations.
>> Simulink
Page 103
Electrical Programming - MATLAB
● Alternately, you may click on the Simulink icon located on the toolbar
as shown:
To start SIMULINK
press this icon
SIMULINK's library browser window like one shown below will pop up
presenting the block set for model construction.
Page 104
Electrical Programming - MATLAB
Page 105
Electrical Programming - MATLAB
Page 106
Electrical Programming - MATLAB
Page 107
Electrical Programming - MATLAB
Page 108
Electrical Programming - MATLAB
● Alternately, you may click on the blank icon located on the toolbar of
the Simulink GUI as follows :
To open an
existing file
press this icon
To creat a new
file press this
icon
Page 110
Electrical Programming - MATLAB
● Choose the sine wave block and drop it on the blank page as :
Page 111
Electrical Programming - MATLAB
● Repeat the previous step with the other needed blocks and arrange
them as shown below :
● Connect between the blocks to get the final model of the problem :
Page 112
Electrical Programming - MATLAB
● To start the simulation and getting the required plots, press the icon
Simulation on the pull-down menu and choose Start , by then the
output will be displayed as :
Page 113
Electrical Programming - MATLAB
Example (1) :
If y 1 = 20 sin(ωt - 30°) and y 2 = 40 sin(ωt + 60°) , express
y = y1 + y2 as a single phasor using SIMULINK blocks.
----------------------- Solution -----------------------
The solution can be carried out using MATLAB SIMULINK
programming by creating the following model-file and run it to get the
result.
● Firstly find the phasor representation of Y 1 and Y 2 as
follows : Y 1 = 20 ∟-30° and Y 2 = 40 ∟60°
● Secondly, create a model representing the two phasors and
their sum using the blocks as displayed in the following :
Constant Sources
Display Sinks
Page 114
Electrical Programming - MATLAB
Page 115
Electrical Programming - MATLAB
Using the Sine Wave and the Scope blocks, the previous example can be
modeled as follows :
Page 116
Electrical Programming - MATLAB
Page 117
Electrical Programming - MATLAB
● In Simulink, create a new model window and drag the following blocks
from the Simulink library window :
Step Sources
Integrator Continuous
Scope Sinks
Page 118
Electrical Programming - MATLAB
● Enter the values of the parameters for each block by setting the mass
m = 2.0 ; the damping coefficient c = 0.5 and the stiffness k=1.
Page 119
Electrical Programming - MATLAB
Page 120
Electrical Programming - MATLAB
Chapter (6)
Database
Applications
Page 121
Electrical Programming - MATLAB
Chapter (6)
Database Applications
Page 122
Electrical Programming - MATLAB
References:
1. Math Works, “Using MATLAB”, Math Works Inc., Ver. 8, 2012.
2. Math Works, “Learning MATLAB”, Math Works Inc., Ver. 8.1, 2013.
3. Math Works, “Using Simulink”, Math Works Inc., Ver. 8, 2012.
4. Andrew Knight, “Basics of MATLAB and Beyond”, Chapman and
Hall/CRC, 2000.
5. Steven T. Karris, “Circuit Analysis I and II with MATLAB
Applications”, Orchard Publications, Fremont, California, 2008.
6. C. Moler, “Numerical Computing with MATLAB”, Prentice Hall,
Englewood Clifs, NJ, 2008.
7. Brian H. Hahn and Daniel T. Valentine, “Essential MATLAB for
Engineers and Scientists”, Fourth Edition, Academic Press
ELSEVIER, 2010.
Page 123