KEMBAR78
Electerical Programming | PDF | Matrix (Mathematics) | Matlab
0% found this document useful (0 votes)
8 views123 pages

Electerical Programming

The document outlines the course content for Electrical Programming using MATLAB at Helwan University, covering topics such as MATLAB basics, mathematical manipulation, linear algebra, circuit analysis, and data visualization. It introduces MATLAB as a powerful tool for numerical calculations and graphics, emphasizing its capabilities in handling arrays and performing complex operations. The course aims to equip students with practical skills in MATLAB for applications in engineering and mathematics.

Uploaded by

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

Electerical Programming

The document outlines the course content for Electrical Programming using MATLAB at Helwan University, covering topics such as MATLAB basics, mathematical manipulation, linear algebra, circuit analysis, and data visualization. It introduces MATLAB as a powerful tool for numerical calculations and graphics, emphasizing its capabilities in handling arrays and performing complex operations. The course aims to equip students with practical skills in MATLAB for applications in engineering and mathematics.

Uploaded by

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

Helwan University

Faculty of Engineering – Helwan


Dept. of Electrical Power & Machines Eng.

Electrical
Programming
POW 101

Dr. Mohiy Bahgat

2016
Electrical Programming - MATLAB

Course Contents

Chapter 1: Introduction to MATLAB


1.1. MATLAB Command Prompt
1.2. Scripts
1.3. Comments
1.4. The Input / Output Functions
1.5. Basic Reading and Writing Data from a File
1.6. Saving and Loading MATLAB Files

Chapter 2: Mathematical Manipulation


2.1. Data Types and Operations on Point Values
2.1.1. Boolean and rational
2.1.2. Strings
2.1.3. Complex numbers
2.2. Matrix Manipulation
2.2.1. Declaring arrays
2.2.2. Properties of arrays
2.2.3. Array operations
2.2.4. Vectors and basic vector operations
2.2.5. Special arrays

Chapter 3: Linear Algebra and Circuit Analysis


3.1. Program Control Flow
3.2. Loops and Branches
3.3. Linear Algebra - Simple and complicated matrix operations
3.4. MATLAB Circuit Analysis

Page 2
Electrical Programming - MATLAB

Chapter 4: 2-D Plots and their controls


4.1. 2-D Graphics Commands
4.2. 2-D Controls

Chapter 5: MATLAB Simulink Toolbox


5.1. Introduction to Simulink programming
5.2. Mathematical modeling
5.3. Displaying outputs

Chapter 6: Data Base Applications


6.1. Introduction to data base
6.2. Data base applications

Chapter 7: Network and Multimedia Components


7.1. Introduction to computer Networks
7.2. Multimedia components

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.

The MATLAB capabilities are:

• It can do quite sophisticated graphics in two and three dimensions.

• It contains a high-level programming language near to “ C ”


which makes it quite easy to code complicated algorithms
involving vectors and matrices.

• It can numerically solve nonlinear initial-value ordinary


differential equations.

• It can numerically solve nonlinear boundary-value ordinary


differential equations.

• It contains a wide variety of toolboxes which allow it to perform a


wide range of applications from science and engineering.

Mathematics is the basic building block of science and engineering, and


MATLAB makes it easy to handle many of the computations involved.
MATLAB should not though as another complicated programming

Page 5
Electrical Programming - MATLAB

language, but as a powerful calculator that gives fingertip access to


exploring interesting problems in science, engineering, and mathematics
using only a small number of commands and functions.

MATLAB was designed to group large amounts of data in arrays and


perform mathematical operations on these data as individual arrays rather
than as groups of data. This makes it very easy to apply complicated
operations to the data, and make it very difficult to do it wrong. For an
overview of the capabilities of MATLAB, type:
>> demo in the help navigator and click

This course is concerning with introducing many of the capabilities of


MATLAB and makes a use of mastering MATLAB by giving an overview
of commands which are useful in many undergraduate courses that cover
linear algebra , ordinary differential equations , mathematical modeling ,
numerical analysis and two or three-dimensional graphics.

MATLAB will be first introduced as a calculator, then as a plotting package


and finally as a simulating program.

• When introducing MATLAB as a calculator, this will help in


understanding the MATALB concepts in manipulating numbers and
variables and getting experience in how to apply the same steps to
matrices rather than individual numbers or variables.

• 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.

• Finally, SIMULINK toolbox of MATLAB will be presented to


simulate systems in a lot of different applications.

Page 6
Electrical Programming - MATLAB

1.1. The MATLAB command prompt


MATLAB is dynamically compiled, which means that, it goes line by line
through the files or codes written for it and performs the calculations
without the need for generating executable files as the case when a code is
compiled by external compiler.

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).

Fig (1.1) – MATLAB starting screen and command prompt

Page 7
Electrical Programming - MATLAB

• MATLAB can perform the functions of a simple calculator from the


command line.

• 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 :

>> [outvar 1, outvar 2, ...] = function_name(input 1,

input 2, input 3,...)

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.

1.2. The current directory and defined path:


It is necessary to declare a current directory before saving a file, loading a
file, or running an M-file. By default, the MATLAB current directory will
be .../MATLAB. After starting MATLAB, the current directory may be

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.

Fig (1.2) – Default MATLAB current directory

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

Fig (1.3) – Setting the MATLAB path.

Also, some other path functions may be used such as :

• addpath, To add a directory to the MATLAB search path

addpath c:\matlab\work

Page 10
Electrical Programming - MATLAB

Page 11
Electrical Programming - MATLAB

• rmpath, To remove a directory from the search path

>> rmpath /home/user/matlab

There are many ways to save to files in MATLAB.

• save - saves data to files, *.mat by default

• uisave - includes user interface

• hgsave - saves figures to files, *.fig by default

• diary [filename] - saves all the text input in the


command window to a text file.
The files are saved in your current directory, as seen on the top of the
window. By default the current directory is ... / MATLAB / work.

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

Fig (1.4) – Opening an m-file using the file menu.

File Naming Constraints:


You can name files whatever you want, with a few exceptions :

• MATLAB for Windows retains the file naming constraints set by


DOS. The following characters cannot be used in filenames :

" / : * < > | ?


• You're not allowed to use the name of a reserved word as the name
of a file. For example, while.m is not a valid file name because

while is one of MATLAB's reserved words.

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)

You must save it as factorial.m in order to use it. MATLAB will


name it for you if you save it after typing the function declaration, but
if you change the name of the function you must change the name of
the file manually, and vice versa.

1.3. The MATLAB M-file Programming:


M-files are macros of MATLAB commands that are stored as ordinary
text files with the extension (m), that is filename.m.

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:

1.3.1. The script files:


The script files do not take input arguments or return output arguments.
Scripts are a type of m-files that runs in the current workspace. So, when
a script file is called from the command line; it will use and manipulate
Page 14
Electrical Programming - MATLAB

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.

You will be presented with the MATLAB Editor/Debugger screen,


where you will type your code, can make changes … etc.

Once you are done with typing, use the following steps to save the file:

Click on Save, in the MATLAB Editor/Debugger screen

Select Save or Save As

Chose a name for your file, e.g., firstprog.m

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.

To open the m-file from within the Command Window type:


Edit firstprog

Press Enter or Return key.

Page 15
Electrical Programming - MATLAB

Or Click on Open

Select Open
Choose the file from the displayed list in the
dialogue box.

Example of a small script file :

% Script file firstprog.m


x = pi/100 : pi/100 : 10*pi;
y = sin(x)./x;
plot(x,y)
grid

This file comprises five statements explained as follows :

1. % this is a comment. All comments are ignored by MATLAB. They


are added to improve readability of the code. In the next two lines
arrays (x) and (y) are created. Note that the semicolon follows both
commands. This suppresses display of the content of both vectors to
the screen.
2. Array (x) holds 1000 evenly spaced numbers in the interval [π/100

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

right division operator (/). This tells MATLAB to perform the

component-wise division of two arrays sin(x) and (x).

3. The command plot creates the graph of the function using the
points generated in the two previous lines..

Page 16
Electrical Programming - MATLAB

4. Finally, the command grid is executed. This adds a grid to the


graph.
5. This file can be invoked by typing its name in the command window
and pressing the Enter or Return key.

1.3.2. The function files:


The function files take input arguments and return output arguments.
Functions are wholly contained in themselves. They possess their own
workspace keeping workspaces separate. This means that all variables
necessary for a particular function must be passed or defined in some
way. This can get tedious for complex algorithms requiring lots of
variables. However, any manipulations of variables are discarded when
the function is exited. Only those output arguments provided by the
function are available to the calling workspace.

1.3.3. Requirements for a function


Custom functions follow the following syntax in their most basic form :
function [ out1, out2, … ] = fun_name(in_arg1, in_arg2)
…………
………… statements
…………
return;

In current versions of MATLAB the return; line is not required. The

fun_name can be anything but it is better, if the m-file name is

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.

Typically output arguments are initialized to empty [ ] or 0 or -1 or


something equivalent for other data types. The reason is that if the
function encounters an anticipated error then the function can return via
the return command with the default values. If the initialization value is
an invalid value then it can easily be checked by the calling function for
any errors which may not throw a MATLAB error.

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 path is

• 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.

1.3.5. nargin & nargout


The nargin and nargout commands are only valid inside functions
since scripts are not passed any arguments.

• The nargin command returns the number of passed input

arguments. This is useful in conjunction with nargchk -

command by entering nargchk(min, max, nargin) where

min is the minimum number of arguments necessary for the

function to operate and max is the maximum number of valid


input arguments.

• The nargout command is useful for determining which output


arguments to return. Typically, the outputs are the end results of
some algorithm and they are easily calculated. However, in some
cases secondary output arguments can be time consuming to be
calculated or require more input arguments than the primary output
arguments. So the function can check the number of output
arguments being requested through the nargout - command.

Page 19
Electrical Programming - MATLAB

1.4. Useful syntax guidelines


1.4.1. Using the semicolon symbol:
Placing the semicolon symbol after every line tells the compiler not to
place that line of code in the command prompt and then execute. This can
make your programs run a lot faster. Also, placing a semicolon after
every line helps with the debugging process.
syms x y z;
w = [x y z];
e = [1 2 3];
t = jacobian(e,w);

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

editor, commented areas are printed in green by default, so they should be


easy to be identified.

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

and Ctrl-T to do the opposite.

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 :

% Calculate average velocity, assuming acceleration

% is constant and a frictionless environment.

force = mass * acceleration

It is common and highly recommended to include a block of comments


explaining what an M file does and how to use it at the first lines of
program text. MATLAB will output the comments leading up to the
function definition or the first block of comments inside a function
definition when a help is asked about the function as follows :

>> help function_name

All of MATLAB's own functions written in MATLAB are documented


this way as well. Comments can also be used to identify authors,
references, licenses, and so on. Such text is often found at the end of an
M-file and might also can be found at the beginning as well. Finally,
comments can be used to aid in debugging,

Page 21
Electrical Programming - MATLAB

1.5. Entering data at the command line:


The input( ) function lets the scripts process data entered at the
command line during the execution of the script file. All inputs are
converted into a numerical values or arrays.
The argument for the input( ) function is the message or prompt needed
to be displayed.

Example :
% test.m
% let's ask a user for x
x = input('Please enter a value for x : ')

Then running the script would produce the output :

Please enter a value for x : 3


x=3

1.6. Basic reading and writing data from a file:


1.6.1. Reading and writing from a file via command line:
The quickest mean of saving and retrieving data is through the binary
formatted files provided by MATLAB whose extension is xxx.mat.
Saving Data: the save command is used to save the workspace data
or specified variables to a file. The following are the different syntaxes of
the save command:

Page 22
Electrical Programming - MATLAB

>> save saves the workspace variables to disk in a file


named matlab.mat

>> save file_name saves all workspace variables in binary to the


file named file_name.mat, the data may be
retrieved with the load command.

>> save file_name X saves only the variable X in binary to the file
named file_name.mat

>> save file_name X Y Z saves the variables X , Y and Z in binary to


the file named file_name.mat , the wildcard '*'
can be used to save only those variables that
match a pattern.

>> save file_name.txt data* -ASCII


saves all data variables to an ASCII file.

>> save file_name , newdata -append

saves new data variables to the file named


file_name by the end of the file.

Page 23
Electrical Programming - MATLAB

Loading Data: the load command is used to load specified variables

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.

>> load file_name X loads only the variable X from the


binary file named file_name.mat

>> load file_name X Y Z loads the variables X , Y and Z from


the file named file_name.mat , the
wildcard '*' can be used to load only
those variables that match a pattern.

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.


• Boolean 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 .

MATLAB stores rational numbers as doubles by default, which denotes


the number of decimal places stored in each number or variable and
consequently, denotes how accurate the values are.

Note: MATLAB represents irrational numbers such as ( pi ) with rational


approximations.

Boolean data numbers: such numbers are either true or false,

represented in MATLAB by a 1 or a 0 respectively. Boolean variables in


MATLAB are actually interchangeable with doubles which means that
Boolean operators can be performed with arrays of doubles and vice
versa. Any non-zero number in this case is considered as true. Most of
the rational operators also work with complex numbers which cannot be
interchanged with Boolean values like the real rationales.

Page 26
Electrical Programming - MATLAB

Rational operators on single values: MATLAB has all the


standard rational arithmetic operators. Such operators are used in
performing the main arithmetic operations on single values or on arrays
using the definition of arrays, in addition to the remainder operator which
gives the remainder of an integer division operation. The arithmetic
operators with their usage are listed below:

Operator name Symbol Example of usage

Addition + a=4+7

Subtraction - b = 18.55 - 14.21

Multiplication * c = 5 * 3.5

Division / d=a/b

Exponentiation ^ e=a^b

Modulo % remainder = mod(a,b)

Array multiply .*

Array power .^

Left matrix divide \

Right matrix divide /

Left array divide .\

Right array divide ./

All of these functions except for the modulus work for complex numbers
as well.

Page 27
Electrical Programming - MATLAB

Boolean operators on single values: Such logical operators


allow the use of multiple tests and give the result as true or false where a
value of zero means false and any non-zero value is considered true. The
Boolean operators with their usage are listed below:

Operator name Symbol Example of usage


AND & if (x > y & a < b)
OR | if (x > y | a < b)
NOT ~ if (x ~ y & a < b)

The negation operation in MATLAB is given by the symbol ~, which


turns any false values into true and vice versa. Moreover, conditionals
( if , switch and try) and loops ( for or while) always look for
statements that are true, so if you want it to do something only when the
statement is false you need to use the negation to change it into a true
statement.

Relational Operators : such operators make the comparison between


quantities to check the relationship between them such as; if they are
equal, one is greater than the other, one is less than the other or they are
not equal, … etc. Equality == returns the value true if both arguments
are equal. This must not be confused with the assignment operator =
which assigns a value to a variable. The relational operators are listed
below:
Operator name Symbol Example of usage
less than < if ( a < b )
greater than > if ( c > d )
equal to == if ( a == b )
less than or equal to <= if ( e <= g )
greater than or equal to >= if ( k >= m )
not equal to ~= if ( a != b )

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 :

>> fstring = 'hello'


If you would like to include a single quote in the string, this can be done
as follows :
>> fstring = '' ''

>> fstring = 'you''re' fstring = you're

It should be remembered that MATLAB treats the strings as array of


characters. Therefore, many of the array manipulation functions will work
the same with string arrays as any other arrays, such as the functions
(size, transpose, findstr, … etc.).

Strings can be displayed either from MATLAB command line or from


inside an m-file using the function disp as follows :

• Displaying a string in the command :


>> fstring = 'hello';

>> disp( ' fstring ' )

>> disp( [fstring 'world' ] )

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

2.1.3. Complex Numbers

Declaring a complex number in MATLAB


Complex numbers in MATLAB are doubles with a real part and an
imaginary part. The imaginary part is declared by using the characters i or
j. For example, to declare a variable as (1 + i) just type:
>> comNum = 1 + i

comNum = 1.000 + 1.000i

>> comNum = 1 + j

comNum = 1.000 + 1.000i

Note that if the character ( j ) is used, MATLAB still displays ( i ) on the

screen. Since the character ( i ) is used as the complex number indicator it


is not recommended to use it as a variable.

When performing arithmetic operations with complex numbers make sure


that the whole number is included by parenthesis in order to get the
intended results.

Arithmetic operations that create complex numbers:


There are several operations that create complex numbers in MATLAB:

• The first operation is to take an even root of a negative number, for


example : >> (-1)^0.5

ans = 0.000 + 1.000i

>> (-3)^0.25

ans = 0.9306 + 0.9306i

Page 30
Electrical Programming - MATLAB

• Secondly, as a consequence of the Euler formula, taking the


logarithm of a negative number also results in imaginary values :
>> log(-1)
ans = 0 + 3.1416i

• In addition, the roots of functions or polynomials founded using

MATLAB built-in function roots or some other root finding


functions will often return complex answers.

MATLAB functions to manipulate complex values:


There are several built-in functions that manipulate complex numbers in
MATLAB. Some of these functions with their syntax are listed below:

• isreal – function : which tells whether a given matrix is real or


complex when programming. It returns 0 if any of the inputs are
complex. For example :
>> A = [1 + i, 3];
>> isreal(A)
ans = 0
>> isreal(A(2))
ans = 1

• real – function : which can be used to extract the real part of a


complex variable.

• imag – function : which can be used to extract the imaginary


part of a complex variable.
>> real(A)
ans = 1 3

Page 31
Electrical Programming - MATLAB

>> imag(A)
ans = 1 0

• abs – function : which can be used to calculate the magnitude


of a complex variable.

• angle – function : which can be used to calculate the angle of a


complex variable.
>> abs(A)
ans = 1.414 3
>> angle(A)
ans = 0.7854 0

Note : MATLAB computes the angle in terms of radians not in degrees,


to convert to the desired degrees system, multiply by the conversion
factor (180/pi) : >> angle(A)*180/pi

ans = 45 0

2.2. Matrix Manipulation


Arrays are the fundamental data type of MATLAB, the former defined data
types representing strings and numbers are special cases of arrays. So, one
can say that arrays in MATLAB are a collection of several values of the
same type stored by default as floating point values of 64 bits. They are
indexed through the use of a single integer or more than one value as an
array of integers.

2.2.1. Declaring a row or column arrays


The arrays can be declared in several ways as follows:

Page 32
Electrical Programming - MATLAB

• The simplest way to create a row array is to give a comma


separated list of values inside a pair of brackets :
>> array = [0, 1, 4, 5]
array = 0 1 4 5
The commas can be omitted for a row array or replaced by blank
spaces. However, the commas make it easier to read and can help
with larger arrays. Accordingly, the commas indicate that the array
will be a horizontal array.

To declare or create a column array the semicolons can be used to


separate the values and all elements of the array must be the same
data type : >> column = [1 ; 2 ; 3]

column =
1

• Arrays can also be multi-dimensional, to create a 2 dimensional


array or a matrix in Linear Algebra terms, a list of comma
separated values should be given representing the matrix rows, in
addition, each row should be separated by a semicolon as follows :
>> matrix = [1 , 2 , 3 ; 4 , 5 , 6]

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]

??? Error using ==> vertcat


All rows in the bracketed expression must have the same number of columns.

2.2.2. Properties of MATLAB arrays and matrices


MATLAB handles arrays by storing them and providing various
information about its size, data type , ... etc. Some built-in functions can
be used to display the array or matrix information as follows :
>> array = [0 , 1 , 4 , 5];
>> length(array)
ans = 4

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

>> array = [0 , 1 , 4 , 5];


>> size(array)
ans = 1 4

Why Use Arrays?


A major advantage of using arrays and matrices is to avoid using loops to
perform the same operation on multiple elements of the array. For

Page 34
Electrical Programming - MATLAB

example, suppose it is needed to add a scalar of (4) to each element of an


array of [5 2 -7] , MATLAB will assume that the constant will be
added to all elements of the array which yields to :
>> array = [5 2 -7];
>> array + 4
ans = [9 6 -3]

The same rule applies to scalar multiplication.

2.2.3. Array operations


Since arrays are the basic data structure in MATLAB, it is important to
understand how to use them effectively. Arrays in MATLAB obey the
same rule as their mathematical counterpart which means by default, the
matrix definitions of operations are used, unless a special operator called
the dot operator is applied.

In MATLAB, vector and matrix are arrays of doubles and MATLAB


considers vectors as matrices with only one row or only one column.
However, there are special functions just for vectors.

Array assignment
The array assignment is done through the equal symbol :
>> a = [1 , 2 , 3]

As it is the case for most interpreted languages, it is not need to declare a


variable before using it, and reusing a variable name in an assignment will
overwrite the previous content. To avoid cluttering the command line of
MATLAB, any command can be post fixed with a semicolon to indicate
that a new statement or command will start:

>> a = [1 , 2 , 3];
Page 35
Electrical Programming - MATLAB

Accessing elements of a matrix


• Accessing the content of an array is done through the operator (),
with the index inside the parenthesis. For example :
>> a = [1 , 2 , 3];
>> a(1)
ans =
1
• Accessing an element outside the bounds will result in an error :
>> a(5)

??? Index exceeds matrix dimensions.

• To access a single matrix element, the (i,j) subscript can be used,

where (i) is the index in the row, and (j) in the column.

• It is also possible to access blocks of matrices using the colon (:)


operator. This operator is like a wildcard; it tells MATLAB that you
want all elements of a given dimension or with indices between two
given values. For example, to access the entire first row of a matrix :

>> 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

• Finally, if the size of an array is not known but it is needed to access


all its elements from a certain index until the end of the array, the
end operator can be used as follows :
>> a = [1 , 2 , 3 ; 4 , 5 , 6]
>> a(1, 2:end) % row 1, columns from 2
until end of the array.
ans = 2 3

• In addition to index addressing, one can also access only elements of


an array that satisfy some logical criterion. For example, suppose
that there is a matrix y = [1.1 , 2.1 , 3.2 , 4.5] and it is needed to
access only the values between 2 and 4, the syntax for this is as
follows:
>> y(y >= 2 & y <= 4)
ans = 2.1 3.2

Rational Operators on Arrays


Classic arithmetic operations + and – can be used on any array in
MATLAB, it also can be applied to vectors and matrices as well. For
example :
>> a = [1 2 3];
>> b = [1 2 1];
>> a - b
ans = 0 0 2

The multiplication by a scalar also works as expected :

>> 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

Warning: Matrix is singular to working precision.


ans =
Inf Inf
Inf Inf

If it is needed to multiply or divide two matrices or vectors on a


component-wise, or to raise all components of one matrix to the same
power, the dot ( . ) operator can be used. The two matrices must have the
same dimensions. For example, for multiplication,
>> a = [1 , 2 , 3];
>> b = [0 , 1 , 2];
>> a .* b
ans = 0 2 6

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.

Boolean Operators on Arrays


The same Boolean operators that can be used for point values can also be
used to compare arrays. To achieve this, MATLAB compares the
elements of the two arrays on a component-wise and returns them in a
logical array of the same size as the two arrays being compared. The two
arrays must have the same size. For example :
>> A = [2 , 4], B = [1 , 5];
>> A < B
ans =
[0 1]

Page 39
Electrical Programming - MATLAB

2.2.4. Basic vector operations


A vector in MATLAB is defined as an array which has only one
dimension with a size greater than one. For example, the array [1 , 2 , 3]
counts as a vector. There are several operations you can perform with
vectors which don't make a lot of sense with other arrays such as
matrices. However, since a vector is a special case of a matrix, any matrix
functions can also be performed on vectors as well provided that the
operation makes sense mathematically. This section focuses on the
operations that can only be performed with vectors.

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];

To determine if a variable among a program is a vector or not before


attempting to use it for a vector operation, one can use the isvector
function. This is useful for error checking.

>> isvector(H)
ans = 1

>> isvector(V)
ans = 1

Another way to create a vector is to assign a single row or column of a


matrix to another variable :

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.

Declaring a vector with linear or logarithmic spacing :


Suppose it is required to declare a vector which varies linearly between
two endpoints, for example, the vector [ 1 2 3] varies linearly between
1 and 3, and the vector [1 , 1.1 , 1.2 , 1.3 , ... , 2.9 , 3] also varies linearly
between 1 and 3. To avoid having typing out all the vector elements :

• MATLAB comes with a convenient function called linspace to declare


such vectors automatically :

>> Lin_Vector = linspace(1,3,21)


Lin_Vector = Columns 1 through 9
1.0000 1.1000 1.2000 1.3000 1.4000
1.5000 1.6000 1.7000 1.8000

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

other points in between. If the third argument is omitted, MATLAB


assumes the needed vector to have 100 elements.

• If, instead, it is needed to have logarithmic spacing, the logspace


function can be used. This function, finds (n-2) points between (10a)
and (10b) as follows :

>> Log_Vector = logspace(1, 3, 21)


Log_Vector = 1.0e+003 *
Columns 1 through 9
0.0100 0.0126 0.0158 0.0200 0.0251
0.0316 0.0398 0.0501 0.0631
Columns 10 through 18
0.0794 0.1000 0.1259 0.1585 0.1995
0.2512 0.3162 0.3981 0.5012
Columns 19 through 21
0.6310 0.7943 1.0000

• If it is needed to generate a vector between two end points with a


specified step, this can be done using the colon symbol ( : ) as follows :
>> x = 1 : 0.2 : 5

x = [ 1.0000 1.2000 1.4000 1.6000 1.8000


2.0000 2.2000 2.4000 2.6000 2.8000
3.0000 3.2000 3.4000 3.6000 3.8000
4.0000 4.2000 4.4000 4.6000 4.8000
5.0000 ]
Vector Magnitude
The magnitude of a vector can be found using the (norm) function :
>> Magnitude = norm(inputvector,2);
For examples :
>> H = [ 1 , 2 , 3];

Page 42
Electrical Programming - MATLAB

>> V = [ 4 ; 5 ; 6];

>> mag_H = norm(H)


Mag_H = 3.7417
>> mag_V = norm(V)
Mag_V = 8.7750
The input vector can be either horizontal or vertical.

Vector dot product


The dot product of two vectors of the same size, when being as a row
vector or a column vector, can be found using the (dot) function as
follows : >> DP = dot(H , V)

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

(this angle is in radians, not degrees)

Vector cross product


The cross product of two vectors of the same size can be computed using
the (cross) function as follows:
>> CP = cross(H , V)
CP = -3 6 -3

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

>> CPMag = norm(CP);


>> theta = asin(CPMag/(mag_H * mag_V))
theta = 0.2257

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.

2.2.5. Special arrays or matrices


MATLAB provides some special types of arrays or matrices using some
built-in functions. The following examples illustrate the usage of such
functions in creating the special matrices :

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

Note : The size inputs (m and n) should be nonnegative integers.


Negative integers are treated as 0.

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

Note : The size inputs (m and n) should be nonnegative integers.


Negative integers are treated as 0.

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

Note: The size inputs (m and n) should be nonnegative integers. Negative


integers are treated as 0.

diag – function :
This function is a tool for creating diagonal matrices and getting the
diagonals of a matrix :

• >> diag(V,K) when V is a vector with (n) components the


result will return a square matrix of order
(n+abs(K)) with the elements of V on the K-th
diagonal.
K=0 is the main diagonal
K>0 is above the main diagonal
K<0 is below the main diagonal

>> 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(V) is the same as diag(V,0) and puts V on the main


diagonal
>> diag(V)
ans =
2 0 0 0 0
0 3 0 0 0
0 0 4 0 0
0 0 0 5 0
0 0 0 0 6

• >> diag(A,K) when (A) is a matrix, the result will return a


column vector formed from the elements of
the K-th diagonal of (A).
>> A = [ 11 25 18 ; 3 5 7 ; 9.5 4.2 1.5];

A= 11.000 25.000 18.000

3.0000 5.0000 7.0000

9.5000 4.2000 1.5000

>> diag(A,3)

ans = Empty matrix : 0-by-1

Page 47
Electrical Programming - MATLAB

>> diag(A,2)

ans = 18

>> diag(A,1)

ans =

25

• >> diag(A) is the main diagonal of (A).

>> diag(A)
ans = 11.0000
5.0000
1.5000

• >> diag(diag(A)) is a diagonal matrix.

>> 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) is the determinant of the square matrix (A).

>> 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) when A is an (n by n) matrix, is a row vector


with (n+1) elements which are the
coefficients of the characteristic polynomial.

>> poly(A)

ans = 1.0000 -17.5000 -196.4000 -680.9000

which means that the characteristic polynomial of the matrix (A)


can be written in the form :
x3 – 17.5 x2 – 196.4 x – 680.9 = 0
The roots of the obtained characteristic polynomial are the matrix
eigenvalues which can easily obtained using the function eig(A).
>> RTS = eig(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

P = poly([1 -17.5 -196.4 -680.9]);

P_value = polyval(P , -3);

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

P1 = [ 1 -3 0 5 7 9]; % The coefficients of p1

P2 = [ 2 0 -8 0 4 10 12]; % P2 coefficients

P1p2 = conv( p1 , p2)

deconv( a , b ) :
This de-convolution function divides polynomial a by polynomial b and

displays the quotient q and the remainder r.

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)

Linear Algebra and


Circuit Analysis

Page 52
Electrical Programming - MATLAB

Chapter (3)

Linear Algebra and Circuit


Analysis

3.1. Program Control Flow


The MATLAB has a group of control statements that enable any
programmer to select at run-time which block of code is executed,
repeatedly execute a block of code or looping back through the block
while keeping track of iterations with an incrementing index variable.

• To make a selection based on whether a condition is true or false,


the if-statement or its combinations can be used.

• To select from a number of possible options depending on the


value of an expression, the switch and case statements are used.

• To loop a specific number of times, the for-statement can be used.

• For basing the loop execution on how long a condition continues


to be true or false, the while statement is more suitable.

3.1.1. IF statement
An if-statement can be used to execute code once when a logical test

or expression returns a true value. On the other hand, an else-

statement following an if-statement is executed if the same


expression is false. The syntax of the flow control statement is :

Page 53
Electrical Programming - MATLAB

• Execute statements if condition is true :

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

a = input( ' Enter any number a = ' ); disp( ' ' )

b = input( ' Enter another number b = ' ); disp( ' ' )

if ( a > b )

disp(sprintf( ' The largest is a = %d \n ' , a))

disp(sprintf(' The difference bet. the numbers a - b = %d ', a-b))

end

if ( b > a )

disp(sprintf( ' The largest is b = %d \n ', b))

disp(sprintf( ' The difference bet. the numbers b - a = %d', 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:

• Receive the coefficients of the equation from the keyboard.

• Calculate the roots of the given equation.

• Display the form of the given equation.

• Display the type of the calculated roots and their values.

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

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);
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))
if 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))
elseif 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))
else
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 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

3.1.2. SWITCH statement


Switch-statements are used to perform one of several possible sets of
operations, depending on the value of a single variable. They are intended
to replace nested if-statements depending on the same variable, which can
become very cumbersome. The syntax is as follows :
Page 57
Electrical Programming - MATLAB

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.

• The otherwise-keyword executes a certain block of code for

any value of variable other than those specified by the case-


statements.

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

3.1.3. Try / catch - statement


The try/catch-statement executes a certain block of code in the try-

block. If the MATLAB detects an error while executing code in the

try-block, it immediately jumps to the start of the respective catch-

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

always be executed, since execution of the try ends when an error


occurs.

Page 60
Electrical Programming - MATLAB

3.2. Loops and Branches


3.2.1. FOR statement
The FOR statement executes code or a block of a program for a specified
number of times using an iterator or a counter. It is usually called a loop
block where the syntax for such a loop is :
for iterator = startvalue : increment : endvalue

…………
………… 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

The factorial of an n number can be written as :


n! = 1 * 2 * 3 * … … * (n-2) (n-1) n
So, the for-loop can be applied to calculate this factorial as follows :
Factorial.m
% Calculation of the factorials starting from 1! and going to 10!
clear
clc
factrial = 1;
disp( ' ' ) , disp( ' ' )
disp( ' The table of factorials from 1 to 10 is : ' )
disp( ' --------------------------------------- ' )
for k = 1 : 10
factrial = factrial * k;
disp(sprintf('\n\t\t %i \t\t\t\t %i ' , k , factrial ))
end

Running MATLAB and entering factorial at the command prompt :

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 :

% Newton's root search method


% File name : Newton_for.m
Clear , clc
x = -3; % Initial guess
counter = 1; % Initial setting for the counter
Maxiter = 20; % Maximum number of iteration to be carried out
xtol = 0.0001; % Tolerance
disp( ' ' ), disp( ' ' ), disp( ' Counter F(x) Root : x ')
% Newton loop :
for j = 1 : Maxiter
fx = x^3 - 5*x + 3;
dfx = 3*x^2 -5;
dx = fx / dfx;
x = x - dx;
disp(sprintf('\n\t\t %i \t\t\t %f \t\t\t %f ' , counter ,fx ,x))
if (abs(dx) < xtol ) % Check for convergence
break
end
counter = counter +1;
end

Page 63
Electrical Programming - MATLAB

Running MATLAB and entering Newton_for at the command prompt,


the following output can be obtained :

3.2.2. WHILE statement


The while-statement also executes a code or a block of a program until a
certain condition becomes false or zero. The syntax for this statement is:
while condition

…………
………… statements
…………

end

Forgetting to change the condition within a while loop is a common cause


of infinite loops.

Page 64
Electrical Programming - MATLAB

Example (7): Calculate the factorial of a number starting from 1


and going to 10 using the while-loop.
----------------------- Solution -----------------------
Factorial_while.m
% Calculation of the factorials starting from 1! and going to 10!
Clear , clc
k = 1;
faactorial = 1;
disp( ' ' ) , disp( ' ' )
disp( ' The table of factorials from 1 to 10 is : ' )
disp( ' --------------------------------------- ' )
while( k <= 10 )
faactorial = faactorial * k;
disp(sprintf('\n\t\t %i \t\t\t\t\t %i ' , k , faactorial ))
k = k + 1;
end

Running MATLAB and entering factorial_while at the command


prompt :

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 -----------------------

% Newton's root search method


% File name : Newton_while.m

clear
clc

x = -3; % Initial guess


counter = 1; % Initial setting for the counter
Maxiter = 20; % Maximum number of iteration to be carried out
dx = 1;

disp( ' ' ), disp( ' ' )


disp( ' Counter F(x) Root : x ')

% 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\t\t %i \t\t\t %f \t\t\t %f ' , counter ,fx ,x))

counter = counter +1;


end

disp(sprintf(' \n\n The final value of the root (x) = %f ' , x))

Page 66
Electrical Programming - MATLAB

Running MATLAB and entering Newton_while at the command prompt,


will display the following output :

3.2.3. Break and Continue


MATLAB includes the break and continue keywords to allow

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

In contrast, the keyword continue causes the program to return back to


the beginning of the loop it is presently in, and to recheck the condition to
see if it should continue executing loop code or not. The code in the loop
after the continue statement is not executed in the same pass.

3.3. Linear Algebra: Simple and complicated


matrix operations.
• Squaring a matrix
a=[1 2;3 4];

a^2; is the equivalent of a*a.

To square each element : a.^2; The period before the operator


tells MATLAB to perform the operation element by element.

• 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

The transpose of a is = [ 1 2 3 ]'

b = a' % this will make b the transpose of a


b=[1
2
3]
• Inverse of a matrix
To find the inverse of a matrix use the MATLAB command inv
noting that the matrix must be square.

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

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

3.4. MATLAB Circuit Analysis Examples

Example (9): Analyzing resistive circuits


using MATLAB
Since the MATLAB is a tool for making mathematical calculations, it
will be used to solve the equations encountered when analyzing resistive
circuits. For example, consider the resistive circuit shown below :

R1 = 1 Ω R2 = 2 Ω R3 = 3 Ω Rs
i

+ +
+ R4 = 6 Ω R6 = 2 Ω + Rp
Vs Vo Vs Vo
- -
R5 = 3 Ω
- -

(a) A resistive circuit (b) Its equivalent


circuit.

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

The solution can be carried out using MATLAB programming by creating


the following m-file and run it to get the result

% Analyzing Resistive Circuits Using MATLAB


% File name : Circuit1.m
clear
clc
% Vary the input voltage from 8 to 16 volts in 0.1 volt steps :
% ------------------------------------------------------------------------
Vs = 8:0.1:16;
% Enter values of the resistances:
% --------------------------------------
R1 = 1; R2 = 2; R3 = 3; % series resistors, ohms
R4 = 6; R5 = 3; R6 = 2; % parallel resistors, ohms
% Find the current, I, corresponding to each value of Vs:
% --------------------------------------------------------------------
Rs = R1 + R2 + R3;
Rp = 1 / (1/R4 +1/R5 +1/R6);
for k=1:length(Vs)
VR(k) = Vs(k) * Rp / (Rp + Rs);
I(k) = VR(k) / R6;
end
% Plot I versus Vs:
% -------------------
plot(Vs, I)
grid
xlabel('Vs, V'), ylabel('I, A')
title('Current in R6')

The output of this m-file is displayed in the following plot :

Page 71
Electrical Programming - MATLAB

Plot of I versus Vs for the given resistive circuit

This plot shows that I will be 1 A when V s = 14 V.

Example (10): Using MATLAB to find out


Thevenin’s equivalent circuit
MATLAB can be used to reduce the work required to determine the
Thévenin equivalent of a circuit such as shown below:

Page 72
Electrical Programming - MATLAB

● First, connect a resistor, R, across the terminals of the network.


● Next, write node or mesh equations to describe the circuit with the
resistor connected across its terminals as shown in Fig (b).
● In this case, the circuit is represented by the following mesh equations :

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 :

The solution can be carried out using MATLAB programming by creating


the following m-file and run it to get the result :

% Using MATLAB to solve the mesh equation of a


% circuit to find the Thevenin equivalent circuit.
% circuit_2_Thevenin.m

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

Example (11): Analysis of steady state


circuits with sinusoidal inputs

Analysis of steady-state linear circuits with sinusoidal inputs using


phasors and impedances requires complex arithmetic. Consider the circuit
shown below :

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

Finally, V o is calculated from V s using voltage division as : 𝑽𝑽𝒐𝒐 =


𝒁𝒁𝟐𝟐
𝑽𝑽𝒔𝒔
𝒁𝒁𝟏𝟏 + 𝒁𝒁𝟐𝟐

The solution can be carried out using MATLAB programming by creating


the following m-file and run it to get the result :

% Analysis of steady state circuits with sinusoidal inputs


% File name : Circuit_3_SS
Clear , clc
% The input voltage source :
w = 2;
A = 12;
theta = (pi/180)*60;
Vs = A*exp(j*theta);
% The circuit elements : resistors, inductor and capacitor:
R1 = 6;
L = 4;
R2 = 12;
C = 1/24;
% Calculation of the equivalent impedances for circuit branches :
Z1 = R1 + j*w*L; % Series impedance.
Y2 = 1/R2 + j*w*C; % Shunt admittance of parallel elements.
Z2 = 1 / Y2; % Equivalent shunt impedance.
% Calculation of the output phasor voltage ;
Vo = Vs * Z2/(Z1 + Z2);
B = abs(Vo);
phi = angle(Vo);
tf = 2*(2*pi/w); % Simulation time for 2 cycles.
dt = tf/100; % Time increment.
t = 0 : dt : tf;
% Plotting the input and output voltages.
%------------------------------------------------
for k = 1 : 101
vs(k) = A * cos(w * t(k) + theta);
vo(k) = B * cos(w * t(k) + phi);

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)

2-D Plots and


their Controls

Page 77
Electrical Programming - MATLAB

Chapter (4)

2-D Plots and their controls


A very useful feature of MATLAB is its ability to generate high quality two-
and three-dimensional plots using simple and flexible commands. All
graphical images are generated in a graphics window, which is completely
separate from the text window where MATLAB commands are typed. Thus,
non-graphical and graphical commands can be completely intermixed.

Graphical images can be generated from either data calculated in MATLAB


or from data which has been generated outside of MATLAB. In addition,
these images can be printed from MATLAB on a wide variety of output
devices, including color ink-jet printers and black-and-white and color laser
printers.

Several plotting commands are used in MATLAB to plot different types of


plotting including the line plots , polar plots , … , etc

4.1. plot – function


This function is a tool for plotting basic two-dimensional plots or
constructing a function in Cartesian coordinates and controlling the line
type, line color, points marking, plotting axes, and adding labels for such
plots. For example, suppose it is needed to plot the functions :
y1 = sin (x) and y2 = ecos(x) for x = [0, 2π]

y3 = sin(cos(x2 - x)) for x = [0, 8]

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)

y1 = sin (x) y2 = ecos(x)

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 linspace-function has two advantages over the colon operator :

• The endpoints of the axis and the number of points are entered
directly as :
x = linspace(first point, last point, number of points)

so it is much harder to make a mistake.

• Round-off errors are minimized so it is guaranteed that (x) has


exactly (n) elements, and its first and last elements are exactly
the values entered into the command.To put all the curves on
one plot, type :
plot(x, y1, x, y2, xx, y3)

Page 80
Electrical Programming - MATLAB

4.2. plot – Controls


Each curve can have a different color, but this will not be visible on a
black-and-white output printer, so, instead of changing the color, the line
type can be changed as follows :

plot(x, y1, x, y2, ' -- ', xx, y3, ' : ')

Page 81
Electrical Programming - MATLAB

where ' -- ' means a dashed line and ' : ' means a dotted line.

In addition, the data points on a curve can be marked by symbols such as


small asterisks to show the locations of each point on the curve as :

plot(x, y1, x, y2, '--', xx, y3, ':* ')

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.

Symbol Color Example

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

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

y Yellow plot(x , y , ' y ')

b Blue plot(x , y , ' b ')

m Magenta plot(x , y , ' m ')

c Cyan plot(x , y , ' c ')

w White plot(x , y , ' w ')

k Black plot(x , y , ' k ')

Table (3.1) - Customizing lines and markers symbol color

Page 83
Electrical Programming - MATLAB

Symbol Line Style Example

- Solid line plot(x , y , ' - ')

-- Dashed line plot(x , y , ' -- ')

: Dotted line plot(x , y , ' : ')

-. Dash-dot line plot(x , y , ' -. ')

Table (3.2) - Symbol line style

Symbol Mark Example


+ Plus sign plot(x , y , ' + ')
o Circle plot(x , y , ' o ')
* Asterisk plot(x , y , ' * ')
. Point plot(x , y , ' . ')
x Cross plot(x , y , ' x ')
s Square plot(x , y , ' s ')
d Diamond plot(x , y , ' d ')
Upward pointing
Δ plot(x , y , ' Δ ')
triangle
Downward plot(x , y , ' v ')
v
pointing triangle
Right pointing plot(x , y , ' > ')
>
triangle
Left pointing plot(x , y , ' < ')
<
triangle
p Pentagram plot(x , y , ' p ')
h Hexagram plot(x , y , ' h ')
none No marker plot(x , y )

Table (3.3) - Marker description


Page 84
Electrical Programming - MATLAB

For example,
plot(x, y1, 'r', x, y2, 'g--o', x, y3, 'mp')

Plots three curves:

• The first is a red, solid line.

• The second is a green, dashed line with circles at the data


points.

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

For example, by dividing the graphics window into 2 vertical, 2


horizontal plots and starting with the first rectangle, one can enter :
subplot(2, 2, 1)
plot(x,y1)
subplot(2,2,2)
plot(x,y2)
subplot(2,2,3)
plot(x,y3)

Page 87
Electrical Programming - MATLAB

When comparing a number of plots, it is important to have the endpoints


of the axes to be the same in all the plots. The axis command can then be
used to rescale all the plots. In addition, it is possible to control the limits
of the axes. The general form of this command is :
axis([ x min x max y min y max ])

• Also, one can force the two axes to have the same scale by :
axis equal or axis image

• and to have the same length by :


axis square

• 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.

• The plot command generates linear axes.

• To generate logarithmic axes use (semilogx) for a logarithmic axis in


(x) and a linear axis in (y).

Page 88
Electrical Programming - MATLAB

semilogx(x,y)

• Or use (semilogy) for a linear axis in (x) and a logarithmic axis in

(y). semilogx(x,y)

• Or use (loglog) for logarithmic axes in both (x) and (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 ‘ )

title( ‘ The variation of Y w.r.t X ‘ )

Page 90
Electrical Programming - MATLAB

• For multiple plots on one graph, sometimes it is needed to put a


legend on the graph to discriminate the different plots on the graph.
(legend) places a legend on various types of graphs (line plots, bar
graphs, pie charts, etc.). For each line plotted, the legend shows a
sample of the line type, marker symbol, and color beside the text
label you specify.This can be done as follows :

plot( x, y1, x, y2, xx, y3 )


xlabel( ‘ X - variation’ )
ylabel( ‘ Y- variation’ )
legend( ' Y1 ' , ' Y2 ' , ' Y3 ' );

Page 91
Electrical Programming - MATLAB

Another example : add a legend to a graph showing a sine and


cosine function:
x = -pi : pi/20 : pi;

plot( x, cos(x), '-ro' , x , sin(x) , '-.b')

legend('cos_x' , 'sin_x' , 2);

MATLAB has two different commands to plot a function directly rather


than plotting a set of points. These commands do not always generate the
correct curve or curves because they know nothing of the actual behavior
of the function. They can have problems with sharp peaks and asymptotes
and other strange behavior of functions.

Page 92
Electrical Programming - MATLAB

4.3. fplot – function :


The first command for direct plotting the functions is (fplot), which can
be executing by simply entering :
fplot(<function name> , <limits>)
where :

• <function name> : is the function is usually generated as an

anonymous function or a MATLAB function or a user generated


function m-file.

• <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 :

Draw the functions given below using the fplot command,


discriminate the two functions using different colors, mark the labels,
and identify each one by a legend :
F 1 (x) = x5 – 3.7 x4 – 7.4 x3 – 1.08 x2 – 1.08 x – 6.8

F 2 (x) = 10^5*(sin(x) + cos(x))

---------------------- Solution -------------------


F1 = @(x) (x^5 –3.7*x^4 –7.4*x^3 –1.08*x^2 –1.08*x – 6.8);
F2 = @(x) (10^5*(sin(x) + cos(x)));
fplot(F1 , [-10 10] , '-ro')
hold on
fplot(F2 , [-10 10] , '-.b')

Page 93
Electrical Programming - MATLAB

xlabel( ‘ X- range ’ )
ylabel( ‘ Y = F(x) ‘ )
legend( ‘ F1(x) ‘ , ‘ F2(x) ‘ )
hold off

4.4. ezplot – function :


The other command which can plot a function is (ezplot), which is more
general than (fplot).

• To plot a function on the interval [-2π , +2π ] enter the following


command :
ezplot(<function name>)

• To include limits as the case of using fplot, enter :

ezplot(<function name> , <limits>)

• In addition, a parametrically defined function can be plotted using


the syntax :
ezplot(<fnc 1> , <fnc 2> , <limits>)
Page 94
Electrical Programming - MATLAB

• Finally, this command can also plot an implicitly defined function,


i.e., f(x, y) = 0, by entering :
ezplot(<2D fnc> , <limits>)

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) ezplot(f, [-2 2])

• fplot and ezplot do not always generate exactly the same


curves. For example :
f = @(x) log(x) + 1;

fplot(f, [-2*pi 2*pi])

ezplot(f)

Page 95
Electrical Programming - MATLAB

fplot generates a spurious plot for x = (-2π, 0) where it plots the

real part of log(x) while ezplot only plots the function for x =
(0, 2π).

fplot(f, [-2π 2π]) ezplot(f)

Also, in : f = @(x) x ./ (x^2 + 0.01);

fplot(f, [-2*pi +2*pi])


ezplot(f)

fplot(f, [-2π 2π]) ezplot(f)

The vertical axes are different and ezplot is missing part of the curve.

Page 96
Electrical Programming - MATLAB

4.5. Histogram plots


In addition to the commands discussed above, the histogram plots for a
given data and error bars plots can be drawn easily using MATLAB. To
plot a histogram of the data stored in the vector (x), type :

hist(x)

• This command will draw ten bins between the minimum and
maximum values of the elements in (x).

• To draw a histogram with a different number of bins, type :


hist(x, <number of bins>)

hist(x, 50)

Page 97
Electrical Programming - MATLAB

• Of course, to get a good histogram you should increase the number


of bins, say to 100, and the number of data points in the vector, say
to 100,000.

• Graphics can also be easily printed from within MATLAB. It can be


printed directly from the graphics window by going into the ’File’
menu item. If desired, the plot can be sent to a file rather than to an
output device. The plot can also be stored in the text window by
using the command print.

Page 98
Electrical Programming - MATLAB

4.6. Polar plots


In addition to the rectangle or cartesian plots, MATLAB can plot polar
functions in terms of θ and r(θ) instead of x and y(x) using the

command polar(r,θ) as follows :

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)

plots the polar curve rho = fun(theta) over the default

domain 0 < theta < 2*pi.

• ezpolar(fun, [a,b])

plots the polar curve rho = fun(theta) over the domain

a < theta < b.

For examples :

ezpolar('sin(2*t).*cos(3*t)')

r = sin(2t) . cos(3t) , 0 < t < 2π

Page 100
Electrical Programming - MATLAB

ezpolar('sin(2*t).*cos(3*t)',[0 pi/2])

r = sin(2t) . cos(3t) , 0 < t < π/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 includes a comprehensive block library of toolboxes for both


linear and nonlinear analyses. Since Simulink is an integral part of
MATLAB, it is easy to switch back and forth during the analysis process
and take full advantage of features offered in both environments.

5.1. Getting started with Simulink


● To start a Simulink session, it is needed to run up MATLAB program
first. Then from MATLAB command window, enter :

>> 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

● To browse the contents of each library, just click or highlight the


library name as needed. For example when clicking on Commonly
Used Blocks , the blocks of this library will be displayed as follows :

Page 105
Electrical Programming - MATLAB

● Similarly, when clicking on Sources , the blocks of this library will be


displayed as follows :

Page 106
Electrical Programming - MATLAB

● Also, when clicking on Sinks , the blocks of this library will be


displayed as follows :

Page 107
Electrical Programming - MATLAB

5.2. Creating a model file using Simulink


To create a new or to open an already existed file and starting simulation
of a problem follow the following steps :
● Use the pull-down menu as :
File new model to create a new file

File open to open an existing file

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

● A new blank page will be opened as :


Page 109
Electrical Programming - MATLAB

● Now it is needed to simulate the functions :


a) S 1 = sin(ωt) b) S 2 = ʃ S 1
● To do this open the block set named Sources as :

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 :

Blocks to be dragged to the model Where located in Simulink library


window browser
Sine wave Sources
Integrator Continuous
Mux Signal routing
Scope Sinks

● 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 :

Blocks to be dragged to the model Where located in Simulink library


window browser

Constant Sources

Magnitude-Angle to Complex Math operation

Display Sinks

Sum Math operation

Complex to Magnitude-Angle Math operation

Gain Math operation

Page 114
Electrical Programming - MATLAB

● Thirdly, start the simulation to get the following result :

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

Example (2): Mass-Spring-Dashpot System Simulation


Consider a mass-spring-dashpot system as shown in figure. The
mathematical model for this system is described by :

𝒎𝒎 𝒙𝒙̈ + 𝒄𝒄𝒙𝒙̇ + 𝒌𝒌 𝒙𝒙 = 𝒇𝒇(𝒕𝒕)


where : m : is the equivalent mass of the system,
c : is the damping ratio,
k : is the spring stiffness,
f(t): is the forcing function in the
x-direction
The response of the system to a unit step input will
be illustrated using Simulink

----------------------- Solution -----------------------

● In Simulink, create a new model window and drag the following blocks
from the Simulink library window :

Blocks to be dragged to the model Where located in Simulink library


window browser

Step Sources

Gain Math Operation

Sum Math Operation

Integrator Continuous

Scope Sinks

Page 118
Electrical Programming - MATLAB

● Re-arranging the system equation to get an expression for the


𝟏𝟏
acceleration, one can get : 𝒙𝒙̈ = ( 𝒇𝒇(𝒕𝒕) − 𝒄𝒄 𝒙𝒙̇ − 𝒌𝒌 𝒙𝒙
𝒎𝒎

● Based on the acceleration equation, the blocks are connected as


displayed in the diagram shown below :

● 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.

● Run the simulation by clicking on the button pressing CTRL+T


to get the system output response from the Scope block as shown
below :

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

You might also like