Programming For Electrical Engineers - MATLAB and Spice
Programming For Electrical Engineers - MATLAB and Spice
ELECTRICAL ENGINEERS
MATLAB & SPICE
This book and the individual contributions contained in it are protected under copyright by the
Publisher (other than as may be noted herein).
MATLAB® is a trademark of The MathWorks, Inc. and is used with permission. The MathWorks
does not warrant the accuracy of the text or exercises in this book.
This book’s use or discussion of MATLAB® software or related products does not constitute
endorsement or sponsorship by The MathWorks of a particular pedagogical approach or particular
use of the MATLAB® software.
All images of LTspice and its icons are owned by Analog Devices, Inc. (ADI), Copyright © 2021.
All Rights Reserved. The images and icons of LTspice are reproduced with permission by ADI. No
unauthorized reproduction, distribution, or usage is permitted without ADI’s written consent.
Notices
Knowledge and best practice in this field are constantly changing. As new research and experi-
ence broaden our understanding, changes in research methods, professional practices, or
medical treatment may become necessary.
Practitioners and researchers must always rely on their own experience and knowledge in
evaluating and using any information, methods, compounds, or experiments described herein.
In using such information or methods they should be mindful of their own safety and the safety
of others, including parties for whom they have a professional responsibility.
To the fullest extent of the law, neither nor the Publisher, nor the authors, contributors, or
editors, assume any liability for any injury and/or damage to persons or property as a matter
of products liability, negligence or otherwise, or from any use or operation of any methods,
products, instructions, or ideas contained in the material herein.
ISBN: 978-0-12-821502-9
Printed in China
iv Foreword
ACKNOWLEDGMENT
Dr. Brown would like to express her deepest thanks to her coauthor, Jim Squire,
whose ingenuity, good humor, and tireless efforts on behalf of this project have
been an invaluable gift. She would also like to thank her family for the gifts of
laughter, love, and time, which have buoyed her throughout the process of writ-
ing, revising, and publishing this book.
Dr. Squire thanks his coauthor, Julie, for managing to keep him on-track with
inspiration, spirit, and grammar (in roughly that order); his wife, Laura, whose
love and support never faltered even through another year of late-night dinners;
and Kevin and Ryan whose curiosity and enthusiasm for learning he hopes is
reflected in this text.
Acknowledgment v
INTRODUCTION
Introduction xi
exception of hardware description language (HDL) modeling of general digital
systems, which deserves an entire course of its own. In short, this textbook offers
both a general introduction to the analog aspects of Electrical Engineering and
a specific overview of the programming packages of matlab and Spice.
Introduction xiii
• M ultisim: Multisim is another popular circuit simulator, similar to Spice.
It is currently more popular among hobbyists, but it is steadily gaining
traction among industry professionals.
• V erilog: Like VHDL, Verilog is another language used to program FPGAs.
Verilog is more common among nondefense contractors in the United
States, and the language looks more like C.
• M athCAD: MathCAD is a hybrid of a spreadsheet and a higher-math-
ematics package, like matlab. It is faster to learn, but it also has less
programming power. MathCAD is commonly used in Civil Engineering.
• A utoCAD, Solidworks, and Inventor: These are solid-modeling pro-
grams designed to create virtual models of two- or three-dimensional
structures. AutoCAD is very commonly used by civil engineers, while
mechanical engineers generally prefer SolidWorks or Inventor. Solid
modeling skills are usually not expected among Electrical Engineering
students, but they are useful to have.
While it would be impressive to have students finish their first semester with a
working knowledge of all of the above programs, we concentrate on matlab and
Spice in this course because:
1. There is not enough time to cover all the packages and languages used
by electrical engineers.
2. Many of the above programs will not make sense until you take more
advanced engineering courses. VHDL and Verilog, for example, first
require an understanding of state machines and combinatorial logic,
topics taught in Digital Logic courses.
3. You will likely find matlab and Spice helpful in future courses, such as
Circuits, Digital Signal Processing, and Electronics.
Each chapter in Programming for Electrical Engineers has two types of problems:
“Practice Problems” and “Lab Problems.” Practice Problems will check your gen-
eral comprehension of specific material from the preceding pages. At the end of
each chapter, Lab Problems present more difficult problems that will challenge
you to synthesize and implement the material you have learned throughout the
previous chapter.
BOXED ITEMS
SHADED CALLOUTS
Callouts like this one are useful, but not essential. They include:
Introduction xv
PRACTICE PROBLEMS
1. What are the two software packages that you will learn
about in this course?
2. Name two programming languages that are commonly
used in Electrical Engineering and which you may learn
in your career, but which are not taught in this textbook.
Describe how they are used.
3. Which of the following advanced Electrical Engineer-
ing courses will build on the computationally intensive
methods you will first encounter in this course: Circuit
Analysis, Semiconductors, Signals and Systems, Digital
Signal Processing, Microcontrollers, C Programming, and/
or Electronics?
4. Given a choice between C or C# to write a Windows pro-
gram that would run on a PC, which would you use?
5. What software package would you use to write a pro-
gram that runs on both Linux and Windows: Java or C#?
6. If you wanted to learn to make prototypes using a
rapid-prototyping machine (also known as a three-
dimensional printer), would you model them in Solid-
Works or AutoCAD, assuming you were planning on
sharing the work with Mechanical Engineering students?
• S tart matlab
• Change its working directory to your data folder
• Use matlab as a basic calculator
• Create and inspect variables
• Save and load variables
• Get help on syntax from within matlab
• Create vectors in matlab
• Plot data
• Export commands and graphics into Microsoft Word
• Use keyboard shortcuts, like the arrow keys
The matlab program icon is shown below. matlab may take a minute to load,
especially if the installation includes many toolboxes, or if this is the first time
it has been run. matlab will open its standard workspace, as shown on the
following page.
Directory Control
matlab is composed of several controls and windows. The most important window is the center “command” window,
shown above, into which all matlab commands are entered.
If the matlab environment looks substantially different from the image above,
set the tab control in the upper left to home and choose default from the drop-
down layout control in the upper toolbar. Keep the tab control in the home
position; the other positions offer various wizards (for example, to assist in plot-
ting or filter design) that tend to be more cumbersome to use than learning the
direct syntax, as is described in this text.
Next, create a data folder and make it matlab’s current working directory
(i.e. the directory in which matlab expects to find the user’s data and programs):
1. Locate the directory control in the toolbar (top left) of the main window.
2. Use the directory control to navigate to your data directory.
3. Inside your data directory, create a new subfolder for your EE course.
4. Inside that folder, create a subdirectory called “Chapter 1”.
5. Note that the “Current Directory” input box in the toolbar now points to
your “Chapter 1” working directory.
Notice that if you do not save your calculation result into a variable, matlab will
save it into a variable called “ans,” short for “answer,” so you can reuse it in the next
calculation, like this:
⨠ 2 + 3
⨠ ans / 10
returns 0.5
PRACTICE PROBLEMS
Charge
The amount of water (measured in gallons) is like electrical
charge (measured in Coulombs, or “C”). Engineers typically
use the variable “Q” to stand for the amount of charge,
such as Q1 = 0.023 C.
Current
The quantity of water flowing past a point
(measured in gallons per second) is like electrical current
(measured in Amps, or “A”). Engineers use the variable “I”
to stand for current, such as I2 = 12 A.
Q=I t
WLPH
W
DIGGING DEEPER
Those who have taken calculus will recognize that the
above formula for constant current Q = I × t generalizes
to: t1
Q = ∫i (t ) dt
0
for changing current i(t). Yet the concept remains that the
current Q is equal to the area under the current graph.
VARIABLES
Variable names must begin with a letter. They may be any length, and capital-
ization matters. Electrical engineers tend to name resistors as R, R1, R2, R3, etc.,
capacitors as C, C1, C2, frequency as f, and time as t. Note that matlab considers
R1 and r1 to be two different variables.
Variables may be composed of letters (lower and uppercase), numbers (but not
as the leading character), and the underscore _ character.
Once a variable is created, it stays defined until you shut down matlab or explic-
itly delete the variable. It is rare to need to delete a variable, but in case you do,
it is done using the clear command, as follows:
⨠ clear('R27')
Every time matlab is run, it starts “clean,” with no user-defined variables from pre-
vious sessions. To find what variables are currently defined, examine the right-
most window in the matlab environment called the “Workspace” window. The
graphic below shows R1 and f were defined in the middle “Command” window,
and in the right “Workspace” window, f and R1 now appear with their current
value:
Variables in matlab defined in the middle command window are reflected in the workspace windows on the right.
Which variables are valid? If they are not valid, explain why.
5. TheAnswerIs42
6. SePtEmBeR21
7. 2B_or_Not2B
8. R1
9. Current&7
or:
a=7;
3 a
will all return error messages.
a=7;
3*a
which returns 21.
2
10.
4π Hint: the square root function is sqrt().
7
1
11. 1 1 if R1 = 6 and R2 = 12
R1 + R2
Pump creating a
Voltage source + –
pressure difference
Narrowed pipe
Resistor
resisting water flow
Pumped water system (left) and analogous electrical circuit (right). The pump creates a pressure
difference to encourage water to flow through a restricted pipe, as the voltage source (e.g. a battery)
creates a voltage difference, causing electrical current to flow through a resistor. The resistance in the pipe
and circuit are both unavoidable and necessary to keep infinite current from flowing.
FORMATTING NUMBERS
DIGGING DEEPER
Curious as to why matlab keeps about 16 digits
of internal precision, rather than exactly 16 digits?
matlab displays numbers in base 10, but internally
works with them in base 2. It stores them in exactly 52 base-2 digits. In
base 10 this is log10(2^52) or 15.6536 digits.
SCIENTIFIC NOTATION
Very large and very small numbers are more easily read in scientific notation.
For example, a typical capacitor used in our field is a 6.8·10−12 Farad capacitor.
It would be much harder to pick one out from the parts cabinet if its label read
0.0000000000068. In matlab, one can enter values in scientific notation using
this shortcut (given for the above example):
⨠ 6.8e-12
Notice that there is no space between the 6.8 and the e; this is not implied mul-
tiplication (which matlab does not do), but rather a shortcut that gives the same
result as entering 6.8*10^(-12), and yet is easier to enter and read (and internally
for matlab, faster to process). matlab evaluates this input as follows:
⨠ 6.8000e-12
PRACTICE PROBLEMS
15. Use matlab to evaluate e−5. ©
RECALL
There are 360 degrees and 2π radians in a circle. The
conversion factor must therefore be the ratio, 180/π or
π/180. There are more degrees in any angle than radians,
so to convert to degrees multiply by 180/π. There are fewer
radians than degrees in an angle, so to convert to radians
multiply by π/180.
CREATING VECTORS
So far, matlab variables have been scalars, e.g., single numeric values like a = 57.
matlab variables can also be collections of numbers called vectors. Vectors are
defined in square brackets like this:
⨠ y = [12 3 -45 2.7 pi]
Most common mathematical functions will operate on each of the numbers
within the vector, such as exp(), log(), cos(), and the others we have dis-
cussed so far. Using the y vector defined above,
⨠ cos(y)+1
yields
ans =
1.8439 0.0100 1.5253 0.0959 0
Modes: Modern DMMs may seem imposing at first sight, but you
will soon be using them like a pro. To measure a voltage, first set
the selector switch to DC voltage. Possible modes usually include:
• AC (varying) voltage, marked with
• DC (constant) voltage, marked with
• C current
A
• DC current
• Resistance
Probe Tips: The red probe goes to the more positive end, and
the black tip to the more negative end. For the DMM pictured
here, the battery, nominally marked 1.5 V, actually reads 1.78 V. If
the probe tips were reversed, so that the red probe were at the
negative end of the battery, the DMM would read −1.78 V.
Regularly spaced vectors can quickly be created using a colon using the format
start : increment : end. It is easiest to understand with the following examples:
⨠ x = 0 : 0.25 : 2.5
is equivalent to
⨠ x = [0 0.25 0.5 0.75 1 1.25 1.5 1.75 2 2.25 2.5]
Random vectors can also be quickly created using the rand() function. A vec-
tor with N numbers in it can be created using rand(1,N). For instance:
⨠ x = rand (1,10)
returns (this time, since it will return different random numbers for you, or they
would not be random)
x =
Columns 1 through 6
0.1576 0.9706 0.9572 0.4854 0.8003 0.1419
Columns 7 through 10
0.4218 0.9157 0.7922 0.9595
The next chapter will more fully explore vectors and their two-dimensional
versions called matrices.
It should be clear why you want to terminate the x and y definitions with an
output-suppressing semicolon; if not, enter the above commands without the
terminating semicolon and observe what happens!
PRACTICE PROBLEMS
17. Plot a triangle with vertices at x = [0 1 0.5] and y = [0 0 0.7].
Hint: You may think you need just three points to define
your triangle, but you will need a fourth to close it, where
the final point is a copy of the starting point. To cut and
paste the figure into a Microsoft Word document, under the
Edit menu in the plot choose “Copy Figure”.
This text is a study guide, not a matlab reference manual. A reference manual is an
exhaustive listing of what every command does, listed alphabetically, but it does
not provide instruction on how to use the system as a whole. By contrast, a study
guide teaches the reader by introducing commands in small, sequential units
that build upon each other. matlab has two different built-in reference manuals:
an abbreviated manual, called “help,” and a more detailed manual, called “doc.”
To get quick, but abbreviated help with the syntax for a matlab command, type
the following:
⨠ help <command>
For instance, you might type:
⨠ help plot
This will return information about the plot command in the command window:
plot Linear plot.
plot (X,Y) plots vector Y versus vector X. If X or Y
is a matrix, then the vector is plotted versus the
rows or columns of the matrix, whichever line up. If
X is a scalar and Y is a vector, disconnected line
objects are created and plotted as discrete points
vertically at X.
plot (Y) plots the columns of Y versus their index.
Various line types, plot symbols and colors may be
obtained with plot (X,Y,S) where S is a character
string made from one element from any or all the
following three columns:
matlab does not remember variables between sessions; that is, when matlab is
started, it starts with no variables defined, except for a few hidden constants like
pi. Once variables are defined, they may be saved or loaded. Variables worth
saving are typically large vectors or matrices holding a lot of data. These may be
very large; for example, a vector defined to hold all the close-of-day stock prices
for IBM would have over 20,000 numbers in it.
To save a variable x, which may be real or complex, scalar or vector, in a file called
“x.txt” in ASCII format (which is a format that you can read and edit in a program
like Notepad), enter the following:
⨠ save ('x'.txt, 'x', '-ascii')
The filename comes first, encased in single quotes, followed by your variable
in single quotes, and then the ‘-ascii’ option to save the data in an easily read
and modified format, with each of these parts separated by a comma. Omitting
the ‘-ascii’ option will save the data as a compressed .mat file, which takes less
disk space but is essentially unreadable by any program other than matlab. If the
above syntax seems difficult to remember, do not worry. As long as you know
the name and purpose of the save() command, you can get help by typing:
⨠ help save
NOTE
MATLAB uses single quotes for strings, not double quotes.
KEYBOARD SHORTCUTS
Very often you will need to repeat a sequence of keystrokes exactly or almost
exactly. This has probably happened to you already, and you will find these key-
board shortcuts very convenient.
To recall previous commands, press the up arrow key ↑. Keep pressing to go fur-
ther back in the command history. Once the command is visible, you can edit it
or run it again by pressing “Enter.”
Formatting Numbers
68e-12 type of scientific notation, here representing 68 × 10−12
format long shows all significant digits (about 16)
format short shows about four significant digits of answer
Trigonometric Functions
cos(), sin(), tan() cosine, sine, and tangent functions given an argu-
ment in radians
acos(), asin(), atan() inverse functions of the above, returning an
answer in radians
cosd(), sind(), tand() cosine, sine, and tangent functions given an
argument in degrees
acosd(), asind(), atand() inverse functions of the above, returning
an answer in degrees
Plots
plot(x,y) plots the set of lines whose horizontal positions are in vector x
and whose vertical positions are in vector y
Keyboard Shortcuts
↑ (up arrow) recall last command
↑↑ recall second to last command, etc.
These problems require more thought than the embedded Practice Prob-
lems that were designed to check general comprehension. For each question
record the matlab command if there is a © next to the problem, and the matlab
result if there is a next to the problem. Example of a question and answer with
both a © requirement:
√
Use matlab to evaluate 4 + 5©
6
Question:
Answer: Command: 4+(5^(1/6))
Result: 5.3077
Vs R1
V1 =
R1 + R2
a. se matlab to define variables Vs, R1, and R2 equal to 12 V, 68 Ω, and
U
12 Ω, respectively. Calculate V1. Hint: Do not use dimensions such as
Volts and Ω in matlab, but remember to write them in your result. ©
b. Repeat the above calculation but with R1 = 13 Ω. Notice how defining
variables can make recalculation easier. ©
3. Modern music synthesizer design leans heavily on signal processing
theory. The note called A4 has a frequency of 440 Hz (cycles per
√
12
second). Each “semitone” above it is 2 times higher in frequency than
the note before it. For example, one semitone higher than A4 has a
√
12
frequency of 440 2 Hz , and two semitones higher has a frequency of
a) sing matlab’s vector functions, evaluate this equation for n = 100, 1000,
U
and 10,000 using the variable n. The first command should be n = [100
1000 10000]. Complete the problem using one additional command
using vectors. Hint: Remember the “dot” notation with vectors. ©
b) Find the % error = (approximate−exact)/exact x 100% for n = 100, 1000,
and 10,000. Remember the exponential function is exp(). Do this in a single
command using vectors. Notice how using variables simplifies the work. ©
7. Using matlab, find the total charge that flows through a circuit with a 2.5 A
current source that has been turned on for 45 seconds. (Remember to give
units in your answer!) ©
9. An electric car motor draws 720 A from a 350 V battery when under full load.
Use matlab to determine:
a) What is the equivalent resistance of the motor? ©
b) How much charge flows through the motor in 2 minutes? Be careful of
time units. ©
11. If you cut a wire and separate the ends in the schematic below, all current stops
flowing. What is the equivalent of cutting the wire in the pipe analogy? Hint: it
is not just cutting the pipe because then water would flow everywhere.
12. A 120 V voltage source is connected across a resistor and 6.8 A of current
flows. Use matlab to compute the value of the resistor. ©
14. A student learning matlab attempts to solve an Ohm’s Law problem for the
voltage caused when I = 2.3 ∙ 10−6 A flows through an R = 45 Ω resistor by
typing the following three lines:
I = 2.3ee-6;
R = 4500 Ohms;
V = IR
Unfortunately, there is one mistake in every one of the student’s three
lines, and semicolons are not one of them. Rewrite each of the three lines
correctly and then use matlab to calculate the answer. ©
15. A 1/8 W slow-blow fuse is rated to blow (open) if ¼ A flows through it for
15 seconds, or ½ A flows through it for 3 seconds, or ¾ A flows through it
for 1/8 second. Write the matlab vector expression that calculates the total
charge that flows through the fuse before it blows in each of these three
scenarios. Use a vector for the currents, a vector for the times, and perform
the calculation using a single vector calculation, not three separate ones. ©
17. Imaginary numbers are commonly used in electrical engineering. Find the
result of the following expression using matlab. ©
j6 √7 √28
4 + j5 4 − j5
P = k πD2 + 2π (L − D)
v2n = 4 kB · T · R
where
v2n is the power of the Johnson noise per Hz bandwidth and is
measured in units of V2/Hz
kB = 1.38∙10−23 Joules/Kelvin
T = temperature in Kelvin
R = resistor value in Ohms
Use matlab to find the v2n for a 620 Ω resistor at temperatures from 275°K
to 300°K in 5°K increments. Do this using vectors so it can be done with
a single command. The answers should be very, very small (less than
billionths of a V2/Hz). ©
24. Create matlab variables: R1 = 22, R2 = 47, and R3 = 68 and then evaluate the
following expression, which calculates the equivalent resistance of all three
resistors in parallel: ©
1
1 + 1 + 1
R1 R2 R3
25. Evaluate the complex expression shown below. The vertical lines enclosing
the complex expression indicate that the magnitude of the complex
expression is taken; this will result in a real number. To do this you will need
to read the help for the abs() command. ©
j26
20 − j26
26. A student attempts to solve the equation R1√5 for R1 = 36 Ω with the
following matlab code:
R1 = 36;
1answer = R1*Sqrt [5]
There are three errors in the code. Write down the corrected code and then
use matlab to compute the correct answer. ©
After completing this chapter, you will be able to use matlab as an advanced
calculator to perform these operations:
• Round and separate a number into its integer and fractional components
• Build and manipulate vectors
• Perform vector mathematics
• Work with complex numbers (Signals and Systems)
• Change rectangular to polar complex number formats (Circuit Analysis)
• Work with strings
• Build and manipulate matrices
• Solve large simultaneous equations (Circuit Analysis)
A vector is simply a list of numbers, e.g., [3, −2.4, π, √3, 7−j2]. It can hold any
amount of numbers, including the special cases of 0 or 1 length. A 0-length
vector is called a null or empty vector and holds nothing. A vector of length 1 is
simply a number, also known as a scalar.
CREATING VECTORS
Vectors can name each component in the list explicitly by placing them inside
square brackets. For example, [3 -2.4 pi sqrt(3) 7-2*j]
NOTE
matlaballows embedded constants such as pi, expressions
such as sqrt(3), and complex values such as 7-j*2.
Entering duplicate values like [3 3 3 3] works for just a few values, but it would
be too time-consuming to use this method to create a vector of 1000 identical
numbers. Instead, use these commands:
NOTE
matlabpermits multiplication of a scalar with a vector. When
used in combination with ones(), this lets one fill a vector
with duplicates of any number.
In the following examples,
4*ones(1,5) is the same as [4 4 4 4 4] and
-pi*ones(1,2) is the same as [-3.14159 -3.14159]
There are two ways to fill a vector with linearly spaced values (e.g., [1 2 3 4]),
depending on whether you know the increment between numbers or the
total number of values you need. If you know the increment use the : operator
[start:increment:end]. For example,
0:0.5:3 is the same as [0 0.5 1 1.5 2 2.5 3]
If you do not know the increment, but know the total number of values, use
linspace, e.g., linspace(start, end, number_of_values).
For example,
linspace(0,3,7)returns [0 0.5 1 1.5 2 2.5 3]
linspace() can also decrement if the end value is less than the start value.
For example,
linspace(10,0,5)returns [10 7.5 5 2.5 0]
DIGGING DEEPER
The numbers produced by the matlab random generator
are not truly random—they are pseudorandom, since
they are generated deterministically by an algorithm.
This algorithm uses a seed number to generate its initial pseudorandom
value; each successive pseudorandom number then seeds the next value
generated. When matlab launches, it initializes its seed according to the
current date and time, measured in hundredths of a second, so it always
appears to generate a new sequence of random numbers.
matlaboffers several methods for working with vectors. The examples below
assume the vector is stored in variable v
Viewing a Vector
To view a vector, type the variable that stores the vector. For example,
v
When a vector is created in matlab, the result is echoed to the screen by default.
This can be a problem if you are creating a vector with several thousand elements.
To suppress the echoing, end the command with a semicolon, e.g.,
v = ones(1,1000);
NOTE
Remember that typing a semicolon at the end will keep
matlab from printing all 1000 numbers when you create
the vector v.
Vector Length
Thus, the matlab command to read the fourth value in vector v and set variable
x equal to it is:
x = v(4)
To set the second value in vector v to π, type:
v(2) = pi
You can retrieve multiple values at once by providing not a single index, but a
vector of indices. For example, to retrieve the third through seventh values of
v = 11:21, type:
v(3:7)
This will return the vector [13 14 15 16 17]. Do you see why? The 3:7 created a
vector of indices, and that vector was used as an index to retrieve those values
of v. You can also set multiple values at once by using vectors both to index your
main vector and to set those values. For example, you can type:
v(3:5) = [1 pi sqrt(2)]
This sets v(3) to 1, v(4) to π, and v(5) to √2.
To specify the first elements (say, the first five elements) of a vector v, you might
type this notation:
v(1:5)
What does “removing an element” in a vector mean? We already know how to set
it to zero; for example, setting the first element in vector v = [1 2 3] to 0 can be
done with the following command:
v(1) = 0;
To fully remove the value means to shorten the length of the vector, and this
is accomplished by setting the value equal to[], the null vector. In the above
example, typing
v(1) = [] changes vector v from [1 2 3] to [2 3].
Now length(v) returns 2.
To insert a 5 into the middle of vector v = [1 2 3 4], type the command:
v = [v(1:2) 5 v(3:4)]
While this command may seem like a syntactic mouthful, it follows from the pre-
ceding steps. v(1:2) returns the first two elements of v, v(3:4) returns the last two
elements of v, and those with the middle inserted value of 5 are all assembled
into a new vector, assigned to v. It could have been assigned to a new vector
called x if the original vector v was needed in other calculations.
PRACTICE PROBLEMS
Given x=20:30, write the matlab commands to
8. Find out how many numbers vector x holds. ©
9. Display the contents of x. ©
10. Retrieve the second value of the x vector. ©
11. Set vector y to equal the second through fifth elements of x. ©
12. Set vector y = x but with a 1 inserted into the front and end
of vector x. That is, y = [1 20 21 22 … 29 30 1], but create y
using the x vector. ©
Other features are more expensive, and you are less likely to
need them as you start out. These features include
• True RMS measurement
• NIST-traceable calibration
• Go/no-go testing
• Bargraph displays
A complex number like 4 + j3 is composed of both real and imaginary parts, and
it is often drawn on the complex plane, shown below:
There are three common ways of writing complex numbers: rectangular, polar,
and complex exponential.
DIGGING DEEPER
Since a positive multiplied by a positive is positive and a
negative multiplied by a negative is also positive, it is not
possible to find two real numbers that when multiplied
together make a negative number. We therefore must
define √ −1 as something that is not real; we call it j so that j2 = −1. It
is ironic that one of history’s great mathematicians, Euler, discovered
several important relationships involving complex numbers, including the
famous Euler’s Identity of ejθ = cos(θ) + j sin(θ), but ultimately dismissed
them, saying they were mathematical curiosities of ultimately no
practical significance. Now they are used throughout signal processing,
communication theory, and control theory.
This may be the most familiar to you. The complex number z in the diagram
(above) is written as the sum of its real part and its imaginary part, or z = 4 + j3.
Mathematicians would write the same number as 4 + 3i; electrical engineers
place the j in front of its coefficient for emphasis. Notice that complex variables
are bolded.
Polar
The same complex number z can also be written as its magnitude, or dis-
tance away from the origin, and the angle that a line drawn from the origin to
the complex number z makes with respect to the positive horizontal axis.
See the diagram (opposite) for a graphical example of z = 5∠ 37˚, or 5∠0.64
radians. Note that this represents the same number as 4+j3, expressed in
rectangular coordinates.
Complex Exponential
Euler’s Identity paved the way for a third representation of complex numbers,
closely related to polar, but which is actually a function that can be evaluated.
Using the above example z = 5ej37°, or z = 5ej0.64 in radians. Note the similarity to
this and the polar form.
matlab uses rectangular notation to enter and display complex numbers. Thus,
to create a complex number like 4 + j3 in matlab, recall that implied multiplica-
tion is not supported and instead type the expression:
z = 4 + j*3
Polar form is written with a magnitude and angle. matlab cannot write the entire
number z in polar form, but it can extract the magnitude and angle components.
The magnitude of a complex number z can be found by typing
abs(z)
The angle in radians is
angle(z)
Convert to find the angle in degrees by multiplying by 180/π:
angle(z)*180/pi
Once the magnitude and angle components are found, the number can be
handwritten in polar notation using the format magnitude ∠ angle or magnitude
∠ angle° if in degrees, e.g., 5∠37°.
You can use trigonometry and the complex plane diagram (shown earlier in this
chapter) to derive the following equations that convert polar to rectangular
form, allowing you to enter polar-notated numbers into matlab.
Given the following complex number in polar form, z = mag ∠ ang, enter it in
matlab as follows:
z = mag*cos(ang) + j*mag*sin(ang)
if the angle ang is in radians, or
z = mag*cosd(ang) + j*mag*sind(ang)
if the angle ang is in degrees.
NOTE
Need characters like ∠, π, and Ω in Microsoft Word?
Find them all using Insert → Symbol using the Symbol
font (important for ∠). Want to write them faster? Try
File → Options → Proofing → Autocorrect → Autocorrect
Options → Math Autocorrect → Check the “Use Math Autocorrect
Outside of Math Regions” option. Then in your document, type \angle
to get ∠, \pi to get π, and \Omega to get Ω. Note that these commands
will only work in the desktop version of MS Word, not the online version.
VECTOR MATHEMATICS
Many functions take both scalar and vector arguments, and with one important
difference, these work as you would expect: functions that take a single argu-
ment, like cos(), operate on each element of the vector independently. Opera-
tors that take two vectors, like +, operate on respective elements of each vector.
For instance, if x = [2 4 7], then cos(x) returns a vector of all three cosines
and x + x returns [4 8 14]. Other functions that you have used that take
vector arguments include addition, subtraction, sqrt(), exp(), and all the
trigonometric functions like sin().
PRACTICE PROBLEMS
16. Given x = [4 2 6], write the matlab command to add 5
to each element. ©
17. Given x = [4 2 6] and y = [2 4 8], write the matlab
command to multiply corresponding elements together. If
matlab returns an error, reread the earlier bolded section. ©
STRINGS
Although strings are not strictly a calculator-like function, matlab treats strings
as vectors of characters.
PRACTICE PROBLEMS
18. If str = 'R1 = 47 ohms', write the matlab command
that isolates the number 47 from the string, converts it into
a number, and stores it in variable R1. ©
Equivalent
Two resistors Water analogy
resistance
R1 R2 R1+R2 R1 R2
Series
R1 R1
R1.R2
Parallel R2 R1+R2
R2
MATRICES
Thus far, the vectors discussed in this chapter have been either a single column
or row of numbers. A matrix is a collection of both rows and columns of num-
bers, e.g.,
2 − 4 1.7
42 √2 0
The dimensions of the matrix indicate how many rows and columns it has, with
the number of rows listed first, followed by the number of columns. Thus, the
2-row × 3-column matrix above is a 2×3 matrix. Matrices are used in digital signal
processing to hold streams of data, where the data streams can be very large.
For example, a 100-second song recorded at the CD-quality of 44,000 samples/
second can be represented as a 2-column × 4,400,000-row matrix. The columns
represent the left and right channels of the signal, and each row represents a
sample, i.e., a snapshot in time of the voltage to be applied to a speaker.
If a matrix has a single row, such as 1x5, it is called a row vector. The vectors
discussed earlier in this chapter are examples of row vectors. A matrix may also
have a single column, like 5x1. These are called column vectors. Matrices may
also have a single row and column; these matrices are scalars, or “regular” num-
bers. Matrices may even be null, meaning they have zero rows and columns;
then they hold nothing.
As with creating vectors, there are several different ways to create matrices:
• Defining components explicitly
• Filling with duplicate values
• Filling with vectors
• Filling with random values
RECALL
The semicolon has another purpose besides separating matrix
rows; when placed at the end of a line, it prevents matlab from
displaying the calculation results.
To create a 20 x 30 matrix called big filled with 7’s, use the fact that matlab
understands multiplying a matrix by a scalar, like so:
big = 7 * ones(20,30);
The semicolon at the end of this command is useful; without the semicolon, the
screen would fill with the 600 copies of the number 7 that it generates.
NOTE
Notice the link between these matrix definitions and vectors
you earlier defined. When you created a vector of five
repeating 1’s by using ones (1,5), you were actually creating a
matrix of one row and five columns.
Matrices filled with random numbers between 0 and 1 may be created using the
rand()function. For instance, to generate a matrix called mrand of three rows
and three columns, filled with nine numbers varying between −1 and +1, type
the following:
mrand = 2*rand(3,3) – 1;
Matrices are addressed using rounded parentheses; always in row, column order;
and always using the convention that the row and column index counting begins
with 1. For example, if
−5 7 2.4
m = [-5 7 2.4; 8 0 9] (x = )
8 0 9
then
x = m(2,3)
will set the scalar variable x equal to 9.
m(2,3) = pi creates the following matrix:
−5 7 2.4
8 0 3.14159
Much like if
v = [-2 -4 -6 -8 -10], then
v(2:4) returns
[-4 -6 -8], we can address parts of matrices using the colon : operator.
−5 7 2.4
x
Using the example matrix m from the previous section, where m =
8 0 9
m(1:2, 1:2)
−5 7
returns the square matrix .
8 0
The colon operator is even more powerful than this. It can be used to specify an
entire row or column using the shortened form: m(:,:). For example, to set x
equal to the second row of m, type:
x = m(2, :);
Now x = [8 0 9]
1
To set the first column of m to (note how a single column of a matrix is a col-
2
umn vector), type:
m(:,1) = [1;2];
1 7 2. 4
Now m = .
2 0 9
Matrix Size
Transpose
Transposing a real matrix interchanges rows for columns. Thus, the matrix on the
left
in the example
below
4 3
4 2 5
2 −4 becomes when transposed.
3 −4 7
5 7
The matlab command to do this is the apostrophe '. For example,
x = [4 3; 2 -4; 5 7]enters the matrix in the upper left, and
y = x' creates the matrix in the upper right.
This can also be used to change column vectors to row vectors and vice-versa.
For example, defining the column vector
resistors = [10; 11; 12; 13; 15]
PRACTICE PROBLEMS
30. What single matlab command will allow you to evaluate the
expression below given the vector of t values t=0:5? ©
cos 2t + 4
π
y=
t+1
Since nodal analysis and mesh analysis are very common methods of circuit
analysis and yield sets of linear real or complex simultaneous equations, solving
simultaneous equations is a basic staple of the electrical engineering curricu-
lum. In matlab, this is accomplished as shown in the following example.
Solve for the various voltages V1, V2, and V3 in the following set of equations:
V1 + 2V2 + V3 = 5
3V1 - V2 + 2V3 = 2
-V1 + V2 - 2V3 = -4
To do this, create an A matrix with the coefficients of the unknown voltages and
a b column vector with the values to the right of the equals sign, as follows:
A = [1 2 1;3 -1 2;-1 1 -2];
b = [5; 2; -4];
The solution is (note the backwards division sign):
V = A\b
When using nodal and mesh methods to analyze the response of circuits con-
taining capacitors and inductors, you will solve sets of complex matrices. There
is no difference as far as matlab is concerned; the A matrix will have complex
values such as for this example solving for complex currents:
A = [1+j 2-j*2; -3+j 3];
b = [j; 2-j];
I = A\b;
On a vintage 2012 computer, matlab can solve a set of 100 equations with 100
unknowns in about 1 ms—less time than it takes to depress the Enter key fully.
DIGGING DEEPER
Matrices can do more than solve simultaneous equations
for circuit analysis; they are essential to manipulating
video, rotating photos, providing equalization to audio
streams, finding particular frequencies present in signals, controlling servo
motors, and are the discrete mathematics counterpart of integration and
differentiation.
PRACTICE PROBLEMS
32. Using the circuit in the previous Tech Tip with R1 = 15 Ω and
R2 = 6 Ω, find the Vin needed to make V1 = 19 V using matlab
and algebra.
Rounding Numbers
round(n) rounds to the nearest integer, so [-3.6 5.7] becomes [-4 6].
floor(n) rounds down to the next integer, so [-3.6 5.7] becomes [-4 5].
ceil(n) rounds up to the next integer, so [-3.6 5.7] becomes [-3 6].
Querying Matrices
length(v) returns the number of elements in vector v.
[r,c]=size(m) returns the number of rows in r and columns in c.
m(r,c) returns the element of m at row r and column c. r and c may be vectors.
m(:, c) returns the column c of m (i.e., all rows, column c).
m(1:4,:) returns rows 1 through 4 of m (i.e., rows 1 to 4, all columns).
m(:, 3:end) columns of m from 3 onwards (i.e., all rows, columns 3 to end).
Complex Numbers
i, j sqrt(-1). Can be used, for instance, as 3 + j*7.
real(z) the real part of complex number z (rectangular coordinates).
imag(z) the imaginary part of complex number z (rectangular coordinates).
abs(z) the magnitude of complex number z (polar coordinates).
angle(z) the angle of complex number z in radians (polar coordinates).
Strings
v = 'Hello' defines a string.
x = str2num('42') changes a string representation of a number to a
number.
Although the example uses a length-4 vector, the command should work
with an s vector of any length of 2 or greater. The answer is a single matlab
command, and the first part is given below. Fill in the part represented by
the ellipses (…). ©
s = (v(1:end-1)+ …)/2
This is called a moving-average filter, and it is used in fields from Electrical
Engineering to stock market analysis.
16. Given a predefined vector v of any odd length, write the matlab
command(s) to extract its center value. For example, [2 3 7] would extract
3, and [1 6 2 9 5] would extract 2. The command should be the same
regardless of the length of the vector it operates upon. ©
17. Find the equivalent parallel resistance of a 5 Ω resistor placed in parallel
separately with each of the standard-value resistors from 1 Ω through 9.1 Ω.
(You already created that vector in Problem 1).
That is, find the equivalent of a 5 Ω resistor in parallel with a 1 Ω resistor,
and repeat that with the 5 Ω in parallel with a 1.1 Ω resistor, etc., up to the
5 Ω in parallel with a 9.1 Ω resistor. Do this in matlab by defining R1 = 5 and
R2 = the vector of resistances you defined in Problem 1. Then define the
single command, and matlab’s result, that answers the question. ©
18. You learned in the previous chapter that plot(x,y) plots an x vector
against a y vector. Create vectors x and y that plot the square wave in the
following diagram. Do not worry about the formatting of the axis numbers,
or whether the square wave touches the top and bottom of the plot
window (the next chapter will cover these and other formatting issues).
19. You learned in the previous chapter that plot(x,y) plots an x vector
against a y vector. Create vectors x and y that plot the sine wave shown
in the following diagram below, where the horizontal axis has a domain
from 0 to 10π. Do not worry about the formatting of the axis numbers, or
whether the sine wave touches the top and bottom of the plot window
(the next chapter will cover these and other formatting issues). For the
purposes of this problem, focus on the shape of the sine wave. Hint: Unlike
Problem 18 above, you cannot explicitly enter values for x and y. Instead,
use linspace() to calculate the x values, choosing enough points to
make the plot smooth and calculate the y values using the appropriate
mathematical function. Record the matlab commands used and the
resulting plot. ©
2 + j7
20. Let z =
23∠ 45°
Use matlab to calculate z and display in both rectangular and polar
notation. Use degrees for the angle in polar notation.
21. Given the complex number 2 ∠ 37° written in polar form, use matlab to
write the same number in different forms. In each case, write the result
1
numerically, rather than as an equation (i.e., 0.7071, rather than or
π √2
cos ).
4
a) Write the complex number in rectangular form ©
b) Write the complex number in complex exponential form (using radians),
and format it so that it looks like the formatting of this example: 4.5ej0.72 ©
After completing this chapter, you will be able to use matlab to do the following:
Electrical engineers use a wide variety of graphs to show data. The most com-
mon types are the line plot, the scatter plot, and the bar plot, as shown below.
The line plot is used to show continuously varying data, much as an oscilloscope
may be used to view a time-varying voltage. The scatter plot is used to show
discretely measured data (i.e., the actual vs. rated resistance of a sample of six
inductors). If there is too much data to display using a scatter plot (i.e., a data set
sampling 10,000 resistors), the data may be grouped into bins and displayed in
a bar plot.
Common types of plots used in electrical and computer engineering are shown above. “Voltage versus time” shows the line plot
(with two differently formatted lines on the same axes), while “Inductance value” and “Resistor value distribution” are examples of
the scatter plot and the bar chart, respectively. In this chapter, you will learn how make all of these in matlab.
The line plot is the most common type of graph. It requires two vectors of equal
length: one that specifies the horizontal coordinates of each point and one that
specifies the corresponding vertical points. In high-school mathematics classes,
horizontal distances are often called x and vertical distances y. In electrical engi-
neering, the horizontal axis is often t for time, and the vertical axis is a voltage
v(t), a current i(t), or a generic signal, such as x(t) or y(t).
matlab will select blue for plot lines by default. To select a different color, such as
plotting the previous example in red, type
plot(t, y, 'r')
where 'r' stands for red.
Color Abbreviation
blue 'b'
green 'g'
red 'r'
cyan 'c'
magenta 'm'
yellow 'y'
black 'k'
white 'w'
DIGGING DEEPER
If you need to embed matlab plots in Microsoft Word, do
not use screen grab tools, which only capture low-quality
bitmaps that will appear blurry when printed. Instead,
select the plot window you wish to copy; choose Edit ->
Copy Figure from the menu; and then paste it into the Word document.
By default, matlab uses solid lines to draw plots; however, other line styles can be
specified, such as dotted, dashed, and dash dot:
Style Abbreviation
Solid '-'
Dotted ': '
Dashed '--'
Dash dot '-.'
Specifying predefined colors and line styles is so common that they are inte-
grated in the plot command itself. Other less-common options, such as choosing
the width of the line or choosing an arbitrary color, are accessed through the
keywords at the end of the plot command, followed by a number or vector.
The line width is set to 1 by default. To make it five times thicker, choose a line-
width of 5 using this command:
plot(t, y, 'linewidth', 5)
Similarly, if you need a color other than one of the eight predefined colors that
matlab provides, use the 'color' keyword, followed by the color specification
in [red, green, blue] coordinates. This is a vector of three numbers, with each
number varying between 0 and 1, that defines how much red, blue, and green
(respectively) are present. This color specification system is a common one in
computer graphics. For example, orange is made with a lot of red, mixed with a
medium amount of green and no blue, so the RGB coordinates [1 0.5 0] yields an
orange hue, which can be plotted using the following command:
plot(t, y, 'color', [1 0.5 0])
Combining Commands
Commands to plot() must be grouped into two parts. The first is the x,y data,
followed by the single-character color and the one- or two-character linestyle.
Any color and linestyle characters must all be grouped together and enclosed
in a single set of quotes, e.g. 'r-' rather than 'r','-'. Commands that are
given in two parts, like 'linewidth', 10, must come at the end. For exam-
ple, to draw the thick red dotted line shown on the next page, use the command:
second part
plot(t,y,'r:','linewidth',10)
PRACTICE PROBLEMS
1. P lot cos(t) from −2π ≤ t ≤ 2π. ©
2. Repeat the above using a dotted, green line, with a width 10
times thicker than the default. ©
Most plots will need a title and labels for each axis. This can be done after the
plot is created using the title, xlabel, and ylabel commands, as shown
in the example below, which plots the first 5 seconds of a decaying voltage
exponential:
t = linspace(0,5,100);
y = exp(-t);
plot(t,y)
title('Decaying Exponential')
xlabel('time (s)')
ylabel('amplitude (V)')
Axis Limits
matlab usually does a good job of choosing vertical and horizontal axis limits,
but not always. For example, to make a right triangle, draw three lines connect-
ing these four points (the last point is the same as the first to close the triangle):
{0,0}, {1,0}, {0,1}, and {0,0}. This corresponds to
x = [0 1 0 0]; y = [0 0 1 0]; plot(x,y)
Here, the figure’s axis limits are scaled to the limits of the figure, making the
edges of the triangle difficult to distinguish from the axes themselves.
PRACTICE PROBLEMS
3. M
any waveforms in Electrical Engineering are derived from
complex exponentials. Plot y = real part of (ejtπ) for 0 ≤ t ≤ 5.
(Remember how to find the real part of a complex number?)
Title the plot “Complex Exponential” and label the horizontal
axis “time” and the vertical axis “Volts”. ©
Grids
You can add an oscilloscope-like grid to your plots with the grid command.
After creating your basic plot, turn the grid on or off using these commands:
grid('on')
grid('off')
Logarithmic axis scaling is useful when plotting values where the independent
(horizontal) or dependent (vertical) variables have dense information for small
values, but progressively spread out larger values. For example, attempting to
plot each of the 145 standard value 5% resistor values from 1 Ω to 1M Ω would
be impossible on a standard, linear-scaled axis because the 0.1 Ω difference
between the 1.0 Ω and 1.1 Ω would not be visible on a scale that extended to
1,000,000 Ω.
To fix this, the horizontal, vertical, or both axes of a plot may be logarithmically
scaled, using the following commands, respectively:
semilogx(horizontal_data, vertical_data)
semilogy(horizontal_data, vertical_data)
loglog(horizontal_data, vertical_data)
These commands are used in place of the plot() command and have the exact
same syntax. For example, to create a plot of log-scaled voltage data in vector v
measured at corresponding times t, using a black line five times thicker than the
matlab default, type
semilogy(t,v,'k','linewidth',5)
Note that a logarithmically scaled axis cannot contain a zero value, since
log(0) = -∞.
–10
Amplitude (dB)
–20
–30
–40
100 101 102 103
Frequency (Hz)
PRACTICE PROBLEMS
5. Plot the following filter response using the above Bode styl-
1
ing: y = . Use logspace to generate logarithmi-
10000 + f 2
cally spaced points in the f vector from 1 Hz to 10,000 Hz.
In other words, the Tech Tip gave the f and y vectors. Now,
calculate them with logspace and the given equation.
Hints:
• If logspace returns infinite numbers, reread its section
in Chapter 2.
• Recall that *, /, and ^ work differently with vector and ma-
trix arguments than with scalars. How do you modify them
to work on respective elements between two vectors?
• While the problem requires you to create your own hori-
zontal and vertical vectors of data, the dB computation
and the logarithmically scaled axis plotting routine is the
same as the example (and indeed, for any Bode plot).
1
H (f ) =
1 + j2π f R C
= 1000;
R
C = 1.6e-6; defines the component values
f = logspace(0,4,100); creates a log-spaced frequency
vector from 1 to 10,000 Hz
H = 1./(1+j*2*pi*f*R*C); calculates the H vector
dB = 20*log10(abs(H)); calculates the magnitude of
H in dB
semilogx(f,dB)
title('Lowpass filter')
xlabel('Frequency (Hz)')
ylabel('Amplitude (dB)')
grid('on')
Just as oscilloscopes often have two channels of input data, so engineers often
graph more than one set of data on the same axes. Both data sets {t1, y1} and
{t2, y2} can be plotted on the same axes with the following command:
plot(t1,y1,t2,y2)
The following commands plot y1 = sin(t) and y2 = cos(t) in the same axes for
0 ≤ t ≤ 6:
t = linspace(0,6,1000);
y1 = sin(t);
y2 = cos(t);
plot(t,y1,t,y2)
There is no limit to the number of lines plotted on one set of axes; for example,
with more calculated values of y3, y4, and so on, one could use a command like
plot(t1,y1,t2,y2,t3,y3,t4,y4,…)
A figure legend enables a viewer to tell the difference between different lines
plotted on the same set of axes. To add a legend to a set of two lines, use the fol-
lowing syntax:
legend('name1', 'name2')
To add a legend to the sin/cos plot in our earlier example, type
legend('sin(t)', 'cos(t)')
The legend may be dragged with the mouse to avoid covering the data.
Legends are especially useful when printing on black and white printers. In that
case, denote the difference between plots by using solid and dashed lines.
PRACTICE PROBLEMS
circuit is found to have a response v1(t) = 2e-t, for 0 ≤ t ≤ 1.
7. A
Adding a capacitor introduces oscillations, making the new
response v2(t) = 2e-t cos(20t), over the same time region. Plot
both v1(t) and v2(t) on the same set of axes, label the axes,
and create a legend. Use as many points as needed to gen-
erate a smooth plot.
Scatter plots use similar data to line plots, but instead of joining each {x,y} pair of
data with lines, scatter plots mark the points themselves with markers. They are
most appropriate when graphing discrete data values, where the linear interpo-
lation between data points that are implied by connecting them with a line may
not be appropriate. To create scatter plots, use the same syntax as for a plot, but
use one of the symbols in the table below instead of a line style symbol:
Symbol Abbreviation
• '.'
o 'o'
× 'x'
+ '+'
* '*'
Δ '^'
□ 's'
The same techniques learned earlier with plot() to specify marker color, title,
axis labeling, and grid also work for scatter plots (now, color specifies the marker
color rather than the line color). You can also specify the marker size with the
'markersize' keyword. For example, the plot from the previous page could
be changed to the plot below with the following command:
plot(x,r,'^','color',[1 0.5 0],'markersize',25)
PRACTICE PROBLEMS
8. F ive 10 kΩ resistors are pulled from a drawer and measured.
Their values are found to be 9.6kΩ, 10.2kΩ, 10.4kΩ, 9.9kΩ,
and 10.0 kΩ. Scatter plot these values using circles as
markers. For the horizontal axis, use the measurement num-
bers 1, 2, 3, 4, and 5. Label the axes and title the plot.
Students often find themselves copying many previously typed lines of com-
mands when modifying complicated plots. There is a way to do this much more
efficiently by creating a matlab script:
1. N
avigate into your personal directory using the matlab folder window
and directory toolbar, as highlighted below:
2. F rom the matlab command window type edit. This will spawn a
separate text editing window. In the text editing window, type the
commands shown below (in this case, to plot a sinc waveform):
t = linspace(-10,10,100);
y1 = sin(t)./t;
y2 = zeros(size(y1));
plot(t,y1,'b-',t,y2,'k-')
3. S ave the file as “figure1.m.” All matlab code files must end with a .m
suffix. The edit window should now look like the figure below:
The extra work to create a script to generate complex plots is often justified
by the ease with which they can be modified. In our current example, you
can make the plot lines twice as thick just by changing the last line to add
'linewidth',2 and rerunning the script.
PRACTICE PROBLEMS
9. C
reate a script to build the sinc waveform without the
horizontal zero line given in the previous example, and then
modify the script to make the line-width five times as thick
as the default. Run the script (do not cut and paste the com-
mands into matlab). Show both the script and the result. ©
Chapter 3: matlab Graphics 101
LAYERING PLOT COMMANDS USING hold()
One of the most powerful abilities of plot() is its ability to layer multiple line
plots on the same axis. There are two different ways to accomplish this:
1. Use the plot(x1,y1,x2,y2) syntax earlier introduced
2. Use plot(x1,y1),hold('on'),plot(x2,y2),hold('off')
Let’s begin by describing the weakness of the first method. You know how to
plot two sets of data {x1, y1} and {x2, y2} with two lines using:
plot(x1,y1,x2,y2)
You also know how to format them individually—for instance, making the first
line red and solid and the second line black and dotted. Recall the commands
must be grouped with the data, as in the example below:
second line
plot(x1,y1,'r-',x2,y2,'k:')
The second black dotted line here is hard to see because it is small. How can
you make the first line thick and the second line thin? Two-part commands like
'linewidth', 5 and 'color', [1 0 1] will not work because they must
appear at the very end of the plot() command, and so they apply to all the
line plots within the plot() command, as shown below:
To obtain the desired effect of just the second (black) line being thicker, one must use the
hold() command to layer two different plot() commands on top of each other. To
do this, plot only the first line, and then turn hold on using hold('on'), as follows:
plot(x1,y1,'r-')
hold('on')
Then plot the second thick black line with the linewidth modifier:
plot(x2,y2,'k:','linewidth',5)
Do not forget to turn hold off, or the next plot you create will continue to layer
on top of the current plot:
hold('off')
BAR PLOTS
A bar plot is a convenient way to visualize large quantities of raw data grouped
into bins. For example, if a large class completes a lab and measures the follow-
ing voltages across a capacitor:
Then to graph this relationship, use the same syntax as the plot command, but
use bar(). As always, the horizontal data go first, followed by the vertical data:
v = 3.3:0.1:3.7;
n = [3 12 34 25 9];
bar(v,n)
Bar plots can be colored and also grouped into different series as shown below;
type help bar for more information.
PRACTICE PROBLEMS
11. Digital logic gates have a (usually undesired) delay between
when an input signal changes and when the gate responds,
called propagation delay tp. The following propagation
delays are tested for the common 74LS04 chip, a NOT gate.
Create a bar plot displaying the above values. Label the axes
and give it a title. Hint: Rather than converting very small
numbers like 2.5 ns to 0.0000000025 s, leave it as 2.5 and
label the appropriate axis as “time (ns)”.
You have learned how to plot multiple items on the same set of axes using
hold()or plot(x1,y1,x2,y2). Sometimes you may want to group mul-
tiple separate axes in the same plot as in the figure below, which shows the
frequency response of a Butterworth lowpass filter plotted against various com-
binations of axis scaling. Note that neither hold nor plot can put these on the
same set of axes, since it is the same data plotted using different axis scalings.
Instead, use the subplot() command. This command divides the master plot
into rows and columns of subplots (two rows and two columns in the above
example) and sets the “active” subplot, so that the next plot() command will
draw into it. To create a set of r rows by c columns of subplots and to set the
active sub-plot to p, use the command:
subplot(r,c,p)
As an example, the following commands create a set of two long, narrow plots,
one over the other, the top one graphing v1(t) = sin(t) and the bottom graphing
v2(t) = a triangle wave, for 0 ≤ t ≤ 4π:
t1 = linspace(0,4*pi,1000);
v1 = sin(t1);
t2 = linspace(0,4*pi,9);
v2 = [0 1 0 -1 0 1 0 -1 0];
subplot(2,1,1)
plot(t1,v1)
title('sin(t)')
subplot(2,1,2)
plot(t2,v2)
title('triangle wave')
There are two fundamentally different methods to gain complete control over all
aspects of plots:
• the interactive plot editor
• handle graphics
To enter the interactive plot editor, first create a plot, and then from the plot’s
figure window menu, choose Tools → Edit Plot.
The Figure Window (left), the Axis Window (middle), and Data Set (right) selected when in Edit Plot mode.
Once the desired item is selected, double click to enter the editor. The editor
is context-sensitive and will offer choices dependent on the currently selected
item. Because it is graphical and interactive, the interface is very intuitive to use.
This is the primary benefit to using this method: it is fast.
Handle Graphics
Figure Window
get(gcf) lists figure window properties. There are about 60 of these proper-
ties, including:
'position', [x,y,width,height] sets the size and location of
the figure window relative to the desktop.
'color', [r,g,b] sets the color, in [red green blue] coordinates, for
the background of the figure window
Axis
get(gca) lists all axis properties (there are over 120), including:
'position', [x,y,width,height] sets the size and location of
the axis window relative to the figure window
'xtick', 1:10 sets the numeric position of the tick marks along the
x axis
'fontSize', 12 sets the font size in points of the text labeling the axis
'visible', 'off' makes the axes invisible but keeps visible the data
that they display
Data
h = get(gca,'children');get(h) lists the properties of the plotted
data. The number of these properties depends on the type of plot, but data for a
line plot have about 36 of them, including:
'markerfacecolor', [r,g,b] sets the fill color for the data markers
'markeredgecolor', [r,g,b] sets the color for the outside border
of the data markers
'linecolor', [r,g,b] sets the fill color for the data markers
GUI programs.
To set the properties, use the set() command instead of the get() command,
and use the two-part keyword/value for the property you wish to set, e.g.,
TEXT ANNOTATIONS
Greek Symbols
Superscripts, like powers, such as t2, and subscripts, like V1, are easy to create
in matlab text if the superscript or subscript is just a single character: use ^ or _
respectively. The following command creates the title V1(t) = f(t2):
title('V_1(t) = f(t^2)')
PRACTICE PROBLEMS
16. Graph v1(t) = 2 e−λt, 0 ≤ t ≤ 0.5, where λ = 4; label the vertical
axis “v1 (V),” and give it the title “2e−λt, λ = 4”.
To graph this between −15 ≤ x ≤ 15 and −15 ≤ y ≤ 15, first create x and y matri-
ces using meshgrid(), which can be thought of to be a 3D counterpart of
PRACTICE PROBLEMS
17. Create a surface plot of the following function using a grid
spanning both x and y from −10 to 10.
x y
z (x , y) = sin cos
3 3
Line Plots
plot(x,y) plots the x vector against the y vector
plot(x,y,'r-') red, straight lines. g, b, k = green, blue, black. -, --, : = solid,
dashed, dotted
plot(x,y,'r-', 'linewidth',5) plots using a line width 5x the default
plot(x,y, 'color',[r g b]) plots using a line with color specified by
r, g, and b values from 0 to 1
plot(x,y,'b-',x2,y2,'r:') plots two lines on the same axes (first a
blue solid line, then red dotted)
semilogx(x,y) plots using a logarithmic horizontal axis
semilogy(x,y) plots using a logarithmic vertical axis
loglog(x,y) plots using logarithmic horizontal and vertical axes
Scatter Plots
plot(x,y,'k.') plots points. Use ., o, and x for dot, circle, and x markers
plot(x,y,'o','markersize',10) plots using a marker 10x default size
Bar Plots
bar(x,y,'b') creates a blue bar plot. Other colors are same as plot().
Handle Graphics
get(gcf), get(gca) returns all settable option names for current figure
and axes
get(get(gca,'children')) returns all settable option names for
current data set
set(gcf, 'keyword',val) sets the figure option named “keyword” to val
set(gca, 'keyword',val) sets the axis option named “keyword” to val
set(get(gca,'children'),'keyword',val) sets the data set option
named “keyword” to val
LAB PROBLEMS
2. A
commonly used function in digital signal processing is the Hamming
window and its variants. The equation for this function is shown below:
2πt
w(t) = k − (1 − k) cos , which is plotted over 0 ≤ t ≤ T
T
4. A
student ill-advisedly places a 1 Ω resistor in a US electrical socket, causing
it to dissipate a time-varying power, in Watts, of
2
p(t) = 120 √2 cos (2π60t)
Plot this power for 0.1 seconds using 1000 points, title the plot “power across
1 Ω,” and label the horizontal axis “time (s)” and the vertical axis “power (W).” ©
5. S ignals and Systems classes teach how to design and analyze filters that
remove signals based on their frequency. One such transfer function is
100
H(f ) =
100 + j2π f
where j is the imaginary value √ −1 and f is the frequency in Hz. H(f) is com-
plex, so in complex polar notation, it has a magnitude and an angle. Plot the
magnitude of H(f) as f varies between 1 and 100 Hz. To do this, use log-
space() to create f, and plot the result in a Bode-style plot with the vertical
axis in dB and the horizontal axis logarithmically scaled. ©
high pass filter is a circuit that allows high-frequency signals to pass but
6. A
blocks slowly changing signals. A transfer function for one type of high pass
filter is given below:
j20π f
H(f ) =
10 + j20π f
where j is the imaginary value √ −1 and f is frequency in Hz. H(f) is complex,
so it can be viewed in complex polar notation as having a magnitude and
7. C
ontrol classes teach how to analyze systems that could control a robot
arm’s horizontal motion with varying degrees of damping λ, as described by
the equation:
x(t) = λe−λt
Create three sets of line plots on the same set of axes showing the effect of
λ = 0.5, 1, and 2 over the range of 0 ≤ t ≤ 5, with three different linestyles (e.g.,
solid, dashed, dotted), so each will be readable on a black and white printout,
and create the corresponding legend for it. ©
8. C
omponent values are usually within some tolerance of their nominal value.
A student takes 10 capacitors from a bin labeled “4.7 μF” and measures the
following values, all in μF: 4.81, 4.23, 5.02, 5.25, 4.86, 4.93, 4.60, 4.85, 4.40,
and 4.45. Scatter plot (with points, not connected lines) these values in μF
(e.g., plot 4.81, not 0.00000481) using the measurement number 1–10 for
the horizontal axis. Add horizontal lines showing the limit 10% over and
under the nominal 4.7 value. Hint: A horizontal line can be drawn with two
points. Title the plot “4.7 μF 10% capacitor values.” Note that μ is the Greek
character mu, not the Latin character u. ©
11. Create a plot of a blue square wave y1 and red sine wave y2, both with
heights ranging from −1 to +1 and extending from 0 ≤ t ≤ 4 as shown. Hints:
• Manually specify eight {t1,y1} pairs to make the square wave, but calcu-
late the sine wave using {t2,y2} with many points to make it smooth.
• From trigonometry, sin(π t) will fit two cycles in the span of 4 seconds, as
shown. ©
13. Plot the vector of 145 resistor values (from 1 Ω to 1 MΩ) you saved in Chapter 2
using subplot() to create two plot axes over one another. The top one should
have the normal (linear) vertical axis and the bottom one should have a
logarithmic vertical axis. Both axes should have the normal (linear) horizontal
axis and both horizontal axes should count from 1 to 145 for each of the
standard 5% resistor values. Which plot best shows the data? ©
14. Industrial motors and long-distance power transmission often use three-
phase power. The voltages in one such system are shown below, where the
arguments to the cosine function are in radians, not degrees:
vA (t) = 120 √2 cos (2π60 t)
2π
vB (t) = 120 √2 cos 2π60 t +
3
2π
vC (t) = 120 √2 cos 2π60 t −
3
lot the three waveforms vA, vB, and vC for 0 ≤ t ≤ 0.05 seconds. Use 1000
P
points to plot them, plot each waveform in a different color, and use a legend
with subscripts to show which is vA, vB, and vC.
16. Control systems theory can help predict how a system responds to a
sudden change in input, which is called the system’s step response. Three
common types of step response are given in the following equations:
− t
e 20
−t t −t
e 2+ e 2
2
−t t
e 8 cos
5
lot the three responses for 0 ≤ t ≤ 75 seconds using the above equations.
P
Use 1000 points to plot them, plot each equation in a different color, and use
a legend to describe them. In the legend, call the first equation overdamped,
the second equation critically damped, and the third equation underdamped.
18. Common lossy image compression algorithms rely on basis functions that
are similar to the following function:
z (x , y) = sin(x) cos(y)
Plot this function using a grid spanning x and y from −5 to 5 in 0.2
increments. Use the mesh() command to plot. Hint: To get the x and y to
19. Using the IEEE Code of Ethics set out in this chapter, write a one-paragraph
answer to the following case study:
20. You have been tasked by an automotive company to improve airbag safety
by designing a system that either (A) works very well with passengers of
common heights, but fails to protect passengers who are either unusually
tall or short, or (B) works suboptimally for all passengers equally. Which of
the 10 articles of the IEEE Code of Ethics described in this chapter provide
guidance for this choice? How would you approach the decision in light of
the IEEE Code?
OBJECTIVES
4
After completing this chapter, you will be able to use matlab to do the following:
• escribe the differences between matlab scripts and functions and the
D
strengths and weaknesses of each
• Explain what input and output arguments are and how they are used
• Write a function that takes and returns any number of arguments
• Use commenting effectively
• Use logical operators to create relational expressions
• Use if-elseif-else conditional structures
• Create strings with embedded numbers
A matlab program is simply a collection of commands that one could type from
the command line. These commands are grouped together into a file called a
program and are run by typing the file’s name into the matlab command win-
dow. There is nothing one can accomplish from a matlab program that cannot
be accomplished by typing commands at the command line. So why program?
Programs are important because they:
• Simplify repeating a calculation. For instance, instead of having to type
the formula Rparallel = (R1*R2)/(R1+R2) every time you need
it, just create a program called Rparallel.m.
• H ide complexity. A user can call a program called plotFigure2(),
for instance, without having to remember or understand how
plotFigure2() works.
128 Programming for Electrical Engineers
SCRIPTS
There are two fundamentally different types of matlab programs: scripts and
functions. A script file is a collection of matlab commands, saved in a file that
ends in a .m suffix. When executed, it behaves exactly as if the commands were
typed from the command line. All variables created in the matlab session before
the script is run are available inside the script, and any variables created in the
script are left in memory after the script finishes. This means that the user will
need to remember the names of the variables that the script expects and ensure
they exist before calling the script.
PRACTICE PROBLEMS
1. C
reate a script called CurrentSolver that expects to have
the variables V and R defined. It should create a variable
called I and set it equal to the current defined by Ohm’s Law:
V = I R. ©
FUNCTIONS
Scripts require that variables be predefined with specific names before the script
is run, such as R1 and R2 in the previous example. Then the script is run, and the
script creates variables to store the result, Rp in the previous example. A more
complicated script may create intermediate variables to help work out the final
answer. All of these variables still exist when the script exits—the output variable
that holds the answer and any intermediate variables created to help compute
the answer.
Scripts have two problems. First, the script user must know the name of the input
variables and the names of the new variable that the script creates to hold the
answer. If you use someone else’s script, you will have to open up the script in an
editor to figure out what the input and output variables are called. If the script
happened to use the same output variable name that you were already using,
your data would be overwritten by the script.
Another problem is that the script may need to create many intermediate vari-
ables to help compute the answer. All of these intermediate variables remain
in memory after the script exits, potentially cluttering up your workspace with
many undesired temporary variables. If any of these variables happen to have
the same name as variables you were using, your variables would be overwrit-
ten. Both of these problems can be avoided by using functions.
Functions are written the same way that scripts are written, except that they add
an extra first line. This extra line declares the program is a function, defines the
outputs, and defines the inputs. This is called the function declaration, and it
will be discussed in detail in the following section.
Functions are called differently than scripts. Scripts are called by first defining
the input variables and then by running the script. Functions do not require pre-
defining variables; variables are passed into and out of the function using the
following syntax:
outputVariables = functionName(inputVariables)
You have used this already with built-in functions, like these:
y = exp(-6) % The input variable is -6 and y is set
% to the function’s result
x = sin(pi) % The input variable is π and x is set
% to the function’s result
Script Function
Script program Function program
Rp = (R1*R2)/(R1+R2) function Rp = ParallelFunction(R1, R2)
Rp = (R1*R2)/(R1+R2)
Using the script Using the function
R1 = 10 ParallelFunction(10,15)
R2 = 15
returns 6 to the command window. Since it was not assigned
The script creates the variable to a variable, it is assigned to the default variable ans:
Rp = 6 >> ans = 6
Notice that the script requires the input variables to be defined R1 and R2 and
creates the output variable that is always named Rp. Unlike the script, the func-
tion does not require input variables to be defined at all. In this example, the vari-
ables were passed directly in, and passed directly out. One could have defined
them using the same names as the function declaration used, as follows:
R1 = 10
R2 = 15
Rp = ParallelFunction(R1, R2)
But the variables also could have been defined as anything because the func-
tion is not aware of any variables in the command window, except those passed
by the input arguments. For example, the following commands will work just as
well as those in the previous example:
FirstR = 10
SecondR = 15
OutputR = ParallelFunction(FirstR, SecondR)
In fact, the input variables do not need to be separately defined, as this equiva-
lent example shows:
OutputR = ParallelFunction(10,15);
When a function is called by the user in the command line, like so:
ParallelFunction(10,15)
the function begins to execute. It begins with the first line:
function Rp = ParallelFunction(R1, R2)
This first line tells the function to create temporary variables R1 and R2 and
to assign them the values that were passed into the function (i.e., 10 and 15,
respectively). Unlike a script, these temporary variables R1 and R2 will not stay
in memory once the function exits, and they will not interfere with any other
variables in the command window, even if the command window already holds
variables of the same name.
Except for the way variable names are handled, the rest of the function works the
same as a script, or as if it were typed directly in the command line. For example,
Rp = (R1*R2)/(R1+R2)
creates a temporary variable Rp and assigns it the result of the computation,
with the temporary variables R1 and R2. Here the variable Rp is not left in mem-
ory once the program exits, and if the command window had a variable named
Rp, the temporary variable would not interfere with it. Inside the function, no
variables from the command window are accessible.
After the last line of the function is run, the function goes back to its declaration:
function Rp = ParallelFunction(R1, R2)
and returns Rp to the command line. This can be viewed if the user calls the func-
tion in the command line, as follows:
ParallelFunction(10,15)
≫ 6
Or it can be set to a variable of the user’s choice, like so:
Rout = ParallelFunction(10,15)
This creates the variable Rout and sets it equal to 6. In either case, the temporary
variables R1, R2, and Rp defined inside the function will not be left in the com-
mand window’s memory, and if the command window had already defined vari-
ables R1, R2, and Rp, they would not be changed once the function ran.
PRACTICE PROBLEMS
2. S ave the following script to MyScript.m. It takes three vari-
ables, Isource, R1, and R2, and computes current I1.
Rp = (R1*R2)/(R1+R2);
V = Isource*Rp;
I1 = V/R1;
Remove all variables from matlab’s memory by issuing a clear
command. Then initialize the variables and run the script, like so:
R1 = 10;
R2 = 15;
Isource = 5;
MyScript
What are the names and values of the variables in memory after
the script is run? These can be viewed from the Workspace panel. ®
3. The above program is rewritten as the function below and
saved in the file MyFunction.m:
function I1 = MyFunction(R1, R2, Isource)
Rp = (R1*R2)/(R1+R2);
V = Isource*Rp;
I1 = V/R1;
FUNCTION ARGUMENTS
The variables passed into or out of functions are called arguments. We have
seen that these are declared in the first line of the function declaration, e.g.,
function outputArguments = functionName(inputArguments)
This is the most common case. Examples include the built-in function exp()
and sin(). The function is declared as follows, where input arguments are
abbreviated with “…”:
function outputArgument = functionName(…)
For example, a function that converts millimeters to inches could be defined as
function inches = mm2inches(mm)
inches = mm ./ 25.4;
Sometimes you will need to return more than one variable. An example of this is
a program that converts mm to inches and feet. The declaration for multiple out-
put arguments wraps the output variable names in square parentheses, like so
function [output1, output2] = myFunction(…)
For example, a function that converts millimeters to feet and inches could be
written as
function [feet, inches] = mm2ftin(mm)
inches = mm ./ 25.4;
feet = floor(inches/12);
inches = inches - feet*12;
RECALL
The floor() command returns the integer part of its
argument. floor(3.7) for instance returns 3.
The above function must be saved as the file mm2ftin.m and can be called from
the command line using the following syntax:
[myfeet, myinches] = mm2ftin(5000)
Now the variable myfeet equals 16 and myinches equals 4.8504. Notice another
power of using functions. Since you previously created a mm2inches() func-
tion, you could change the second line in mm2ftin() from
inches = mm ./ 25.4;
to
inches = mm2inches(mm)
which simplifies your program by calling a function from within your function.
Occasionally, it is useful for a function to not return any arguments, such as when
a function just displays a plot. An example you have already encountered is the
built-in plot(x,y) command. The declaration for a zero output function is
function myFunction(…)
For example, the following function creates an artistic-looking plot and returns
no arguments to the command line:
function coolPlot()
plot(fft(eye(11)));
Variables are passed into functions in the first-line function declaration state-
ment to the right of the equals sign, as shown below for three input arguments:
function outputs = myFunction(input1,input2,input3)
When this function is called from the command window using the syntax below,
x = myFunction(1,2,3)
then variables called input1, input2, and input3 will be created and set equal to
1, 2, and 3, respectively. The function can also be called using the syntax
x = myFunction(a,b,c)
Whatever the variable a, b, and c hold will now be assigned to input1, input2,
and input3. Variables a, b, and c will not be visible inside the function, but input1,
input2, and input3 will be. Once the function ends, input1, input2, and input3
will be destroyed. Any changes the function makes to variables input1, input2,
and input3 will not propagate outside the function.
Occasionally, a function that does not require any inputs is needed. A function
that always returns a random capacitor value, for instance, could be defined
using the following syntax:
function randCap = RandomCapacitor()
Note there is nothing inside the parentheses since no variables are being passed
into the function. It is called from the command line as follows:
x = RandomCapacitor();
Both input and output arguments can be scalars, vectors, or matrices. For
instance, take a custom simultaneous equation solver that takes the A coeffi-
cient matrix and the b coefficient vector described in Chapter 2 and computes
the result using the following function:
function result = Simultaneous(A,b)
result = A\b
The inputs, A and b, are a single matrix and vector, respectively, although both
could contain thousands of elements.
PRACTICE PROBLEMS
4. W rite the function declaration (that is, write the first line of
the function but not the code that calculates the answer) for a
function that computes the maximum frequency of a square
wave generated by a microcontroller given the frequency
of the microcontroller’s clock. Name the function clock1
and have it take one input called frequency and one output
called squarewave. ©
5. Write the function declaration for a function that takes one
vector of values, such as a list of all standard 5% resistor values,
Example
An earlier Practice Problem involved a script to use Ohm’s Law V = I R to solve for
the current given a voltage and a resistance.
Solution
Input arguments: V, R
Output arguments: I
PRACTICE PROBLEMS
6. C reate a function called SeriesResistance that takes
two resistor values and returns their equivalent series
resistance (which is their sum). ©
7. Create a function called ParallelResistance that takes
two resistor values and returns their equivalent parallel
resistance (which is their product divided by their sum). ©
COMMENTING PROGRAMS
function I = ISolveFunction(V, R)
% ISolveFunction finds current given voltage and resistance
% I = ISolveFunction(V, R)
I = V./R; % this is Ohm's Law V=I R solved for I
x = 20.1844 + 11.0268i
NOTE
Inside the function, the output variable is called “z,” but it was
called from the command line using a completely different
variable “x.” This is one strength of using functions—the
person using the function does not have to know what the function calls its
variables internally.
Courses in Signals and Systems will develop the following equation that describes
a lowpass filter:
1
H (f ) =
1 + j f / fo
Problem
Create a function called lowpass() that takes a cutoff frequency fo and creates a
Bode plot of the magnitude of |H(f)| from 1 ≤ f ≤ 100.
Solution
Since the function takes one number (fo) and returns nothing (it creates a plot),
the function definition line and help lines are
function lowpass(fo)
% lowpass(fo) creates a Bode-style plot of the
% response of a lowpass filter with a cutoff of fo
Then create a frequency vector, logarithmically spaced between 1 and 100Hz:
f = logspace(0, 2, 50); % 1-100Hz = 10^0 – 10^2
Next, compute H(f):
H = 1./(1+j*(f/fo)); % since using vectors, use ./
Now, change that into dB for the Bode plot (see the Recall inset above):
dB = 20*log10(abs(H)); % find the magnitude of H in dB
Complete the plot and label it:
semilogx(f,dB)
title('Lowpass filter')
xlabel('Frequency (Hz)')
ylabel('Amplitude (dB)')
grid('on')
Save the program as lowpass.m and call it from the command line for a 10Hz
lowpass filter as follows:
lowpass(10)
Note that none of the variables created inside the function remain after the func-
tion runs.
PRACTICE PROBLEMS
9. M
odify the above function to return the filter response in dB
rather than plotting it. For example, using fo = 10, a vector of
50 values are returned, the first of which is −0.0432. ©
SORTING
The matlab command sort() takes a vector of numbers and returns them in a
vector sorted from smallest to largest. For example,
vout = sort([4 9 1 -6 0])
returns
vout = [-6 0 1 4 9]
This capability can be useful inside functions that simulate circuit designs over
many different random component value variations and will be used in one of
the lab problems.
Masters
There are two types of master’s degree programs: industrial
and research. This is confusing since there are no standardized
names for each type of program. Some universities offer both,
while others offer only one of the two. Some call one degree a
Masters of Science (M.S.) and the other a Masters of Engineering
(M.Eng.), while some programs call both an M.S. Examining the
graduation requirements will make it clear which course(s) a
particular university offers.
• Industrial M.S.: Industrial M.S. programs prepare students for
jobs in industry. They typically require 8–10 classes. A thesis,
if required, is small, i.e., the equivalent of one or two courses.
It takes typically one full year to complete, with the associ-
ated cost of tuition.
• Research M.S.: This prepares the student for a research posi-
tion and is the first step in earning a doctorate. Coursework
varies widely, from as little as three courses to as much as
required for an industrial masters. A thesis is mandatory
and is a major component of the work. It takes longer than
an industrial masters, often 18–24 months. This is often not
a separate degree program but part of a doctoral degree
program, so tuition cost may be waived in return for work as
a Teaching Assistant (TA) and Research Assistant (RA), de-
scribed below.
Doctorate
Engineering doctorate degree programs are usually spon
sored fully through a mix of Teaching Assistantships (TAs)
Note that one of the most common relational statements, the test to see if two
scalar numbers are the same, is not = but rather ==.
In the example below, the function called password() tests to see if the input
is “secret” and outputs a 1, if so, and 0, otherwise:
function result = password(input)
% password tests to see if the input is
% the string 'secret'
result = isequal(input, 'secret');
LOGICAL OPERATORS
Logical operators operate on logical true (1) or false (0) arguments and are par-
ticularly important to ECE students, since binary true/false signals form the basis
of all digital computers. Common ones are listed below:
If you are familiar with digital gates, the associated digital logic symbols are:
Operator Symbol
AND
OR
NOT
PRACTICE PROBLEMS
11. Create a function called problem11() that takes a scalar
(single number) and returns a 1 if the input is both not an
integer and is negative. Thus problem11(pi) returns 0,
but problem11(-pi) returns 1. ©
Since logical true values are represented by the numeric value of 1, summing the
results will return the total number of operations that evaluates to true. Using
the above example,
sum(b)
or more directly
sum(v>=0)
will return 3.
This is a very common requirement and has its own syntax. Up to this point, vec-
tors have been indexed with a number like v(4) and matrices have been indexed
with a pair of numbers like m(3,4). However, they can also be indexed by a logical
vector or matrix of the same size as shown in the following example. To replace
the negative elements in the following vector with 9’s,
v = [-2 -1 0 1 2]
v(v<0) = 9
Now v = [9 9 0 1 2]
PRACTICE PROBLEMS
12. Create a function called problem12() that takes a vector
of numbers and returns two variables. The first it returns is
a variable called “count” that is the count of all the values
of the input vector greater than 10. The second is a vector
called “result” and is equal to the input, but with all values
greater than 10 replaced with 10. In other words, its function
definition is
function [count, result] = problem12(x)
and as an example of its use
[count, result] = problem12([-5 20 6
11])
causes count = 2 and result = [-5 10 6 10]. ©
Thus far, every matlab program we have discussed has executed every line of code
in it when run. if-end statement blocks are an exception; the code between
the if-end statement only runs if a logical statement is true, e.g.,
if (logical expression that evaluates to true or false)
% Statements here execute if the logical
% expression is true.
% All statements until the closing end are
% conditionally run
end
For example, the following statements duplicate the functionality of abs(x),
which takes the absolute value of x:
if (x < 0) % if x is negative
x = -x;
end % continue program
Notice that each if statement needs to be paired with a matching end state-
ment. Also notice that the statements between the if and end pairs are
indented. Since matlab ignores spaces, these indentations are optional, but they
make the code easier to read.
PRACTICE PROBLEMS
13. Create a function called problem13 that takes a string
and returns a string which is set to the phrase “unlocked” if
the supplied password is “secret” and “locked” otherwise.
© Hints:
• Unlike other programming languages, matlab uses a
single quote' to denote strings, not double quotes “.
• == and ∼= compare numbers; isequal()
and ∼isequal compare strings, vectors, and arrays.
In the previous section, a sinc function was developed that ran one set of code
if x equaled zero and used a second if statement to run a second set of code if
x was not zero. This need, to run one set of code if the logical test is true, and a
different set of code if the logical test is false, is so common that it has its own
syntax: if-else-end.
if (logical expression that evaluates to true or false)
% statements here execute if the logical
% expression is true
else
% statements here execute if the logical
% expression is false
end
The sinc() function developed in the previous section can be simplified using
this syntax, as shown below:
function out = sinc(x)
% sinc(x) takes a scalar, returns sinc
if (x==0) % if x is zero
out = 1;
else
out = sin(x)/x;
end
If there is one outcome of a test that requires special code, we use an if-end
block. If there are two different outcomes that each require special handling, we
use an if-else-end block. If there are more than two outcomes that require
different code blocks to be executed, the if-elseif-elseif-…-else-end
block works, using as many elseif statements are needed for each possible
outcome, with a final and optional else statement handling all remaining cases.
PRACTICE PROBLEMS
15. Create a function called problem15 that computes the
sign function used in control theory. It takes a number and
returns −1 if the input is negative, 0 if the input is zero, and
1 if the input is positive. Use an if-elseif-else-end
construction. ©
To create a string with both text and embedded numbers in it, use sprintf().
For example, the commands
current = 36.5;
s = sprintf('The current is %g Amps.', current);
create a string s with the contents The current is 36.5 Amps.
RECALL
To change a string into a number use str2num(), for
instance, x = str2num('42').
Sometimes you will need to display a result to the command window directly,
rather than setting a string variable equal to it. In this case, use fprintf(),
instead of sprintf(), as follows:
fprintf('Node 1 = %0.2fV\nNode 2 = %0.2fV\n',pi,2*pi);
prints the following to the command line:
Node 1 = 3.14V
Node 2 = 6.28V
Note the trailing \n inside the quotation marks; it is necessary because without
it, the cursor will be left dangling at the last character written (to the right of the
final “V” character in the example just given), and the next character written will
continue from that point, rather than being reset to the beginning of the next
line as expected.
PRACTICE PROBLEMS
17. Write a function called problem17 that takes an AWG
wire size (even sizes 12–24) and returns the following string
(using as an example an AWG of 12) “AWG 12 is 0.0808 inches
diameter, max current 41A.” Use if-elseif-elseif-end
statements to check the wire size and to set temporary wire
diameter and current capacity variables. Then at the end use
one sprintf() statement to create a string using those
temporary wire diameter and current capacity variables that
are returned by the function. ©
As you get used to using these symbols you will find they will
help you do mathematics spanning large intervals easily. For
instance, a 12 μA current through a 4 MΩ resistor generates their
product in voltage, which is 12 × 4 in units of μ (two up from the
center) times M (two down from the center), which is simply 48
times the center, or 48V. No powers of 10 are required!
These resistors have four bands of color that with some practice
can be read by sight according to the following diagram:
Utility Functions
vout = sort(vin) returns vector vout of the elements in vin, sorted from
smallest to largest
sum(v) returns the sum of the values in vector v
Relational Statements
<, <= less than, less than or equal to
>, >= greater than, greater than or equal to
==, ∼= equal to, not equal to
isequal() isequal works with strings, vectors, matrices
Logical Operators
a && b AND, true if both a and b are true
a || b OR, true if either a or b is true
∼a NOT, negates the logical value of a
all(v) true if all logical values in vector v are true
any(v) true if any logical values in vector v are true
Conditional Statements
if (a)-end executes code up to the end if statement a is true
if (a)-else-end executes one set of code if a is true, a different set if false
if (a)-elseif-else-end multiple tests each with different code sets
1. C reate a function called problem1 that takes the values of two resistors,
R1 and R2, and a character code that can be “S” or “P.” It returns the value of
the resistors in series if the code is “S” and in parallel if the code is “P.” The
function definition is as follows:
function Rout = problem1(R1, R2, code)
2. Create a function called problem2 that takes two real numbers, a
magnitude, and an angle in degrees and returns one complex number
whose value in polar coordinates is described by that magnitude and angle.
You may need to review the information about complex numbers from
Chapter 2. The function definition should be
function z = problem2(mag, degrees)
To test it, problem2(10, 30) should return 8.6603 + 5i.
3. Create a function that does the inverse of the above problem; it takes a
single complex number z and returns its magnitude and angle in degrees.
The function definition should be:
function [mag, degrees] = problem3(z)
To test, [mag,degrees] = problem3(1+j) should return
mag = 1.414, degrees = 45
4. A small college stadium uses 250 high-efficiency LED lighting modules.
Each module consumes 500 W of power. If electricity costs $0.000135/W
every hour, write a function that takes the number of hours that the lights
must be on and returns a string containing the cost of electricity used, in
dollars. The function definition is as follows:
function str = problem4(hours)
The answer should be rounded to the nearest cent and the string should
begin with a “$,” as shown in the example below:
problem4(7) returns
$118.13
x y z out
0 0 0 0
0 0 1 0
0 1 0 1
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 1
reate a function called problem16 that takes the values of x, y, and z and
C
returns the result out. The function definition is as follows:
function out = problem16(x,y,z)
For example, problem16(0,1,0) should return 1.
If anything other than a 0 or 1 is input into the function, the function returns
−1. Use the truth table to check your work.
OBJECTIVES
After completing this chapter, you will be able to use matlab to do the following:
FOR-END LOOP
The for-end loop is used to repeat a section of code for a known number of
times, as in the example below:
for i = 1 : 10
disp('ECE is fun');
end
The for-end loop requires the creation of a loop variable, here called i, and a
loop vector, here the set of numbers from 1 to 10. The loop executes as many
times as there are entries in the loop vector, and for each iteration the loop vari-
able takes on a successive value of the loop vector. There can be any number of
command lines inside the for-end loop. Notice how these commands are typi-
cally indented to make them easier to read, much like the commands inside the
if-else-end block are indented.
The code below makes a list of the squares and cubes of several even numbers:
for x=2:2:6
disp([x x^2 x^3])
end
The above code prints the following to the command line:
2 4 8
4 16 64
6 36 216
PRACTICE PROBLEMS
One of the most common uses of a for loop is to index a vector. This permits
complex operations to be applied to vectors. For example, a different way to
accomplish the previous class problem is in the following function:
function ForIndexingVectorExample(r)
vAllResistors = [10 15 22 33 47 68 82];
for i = 1:length(vAllResistors)
rCur = vAllResistors(i);
rp = (r*rCur)/(r+rCur);
disp(rp)
end
This example begins by defining a vector holding all standard values resistors
called vAllResistors. Then it creates a loop variable i which iterates from 1 to the
Up to this point, vector math has been handled with a single operation, for exam-
ple, multiplication of vector v by a constant c is the single operation: v*c. This
operates on the entire vector at once and is very efficient, but some operations
are more easily understood using a for loop that steps through every value
inside the vector. For instance, consider a piecewise-linear function called the
step function and abbreviated u(t), defined and graphed as follows:
The more complex example plot below plots the following mathematical func-
tion from 0 ≤ t ≤ 30:
function plotPiecewiseFunction()
vt = linspace(0,30,1000); % let t range from 0 to 30
vf = zeros(1,1000); % fill with 0’s
for i = 1 : 1000
t = vt(i); % iterate so t will be
% every value in vt
if (t >= 0) && (t < 10)
vf(i) = sqrt(10*t);
elseif (t >= 10) && (t < 20)
vf(i) = 10*exp(10-t);
elseif (t >= 20)
vf(i) = t-20;
end
end
plot(vt,vf)
PRACTICE PROBLEMS
4. C
reate a function that plots the following for −5 ≤ t ≤ 5. Plot
using 100 points.
1− t , t < 0
v(t ) =
et 4 , t ≥ 0
200
180
critical frequency
160
140
120
0 200 400 600 800 1000
simulation number
A new matlab command that can help visualize the results of
Monte Carlo simulations is histogram(). This command bins
the data and plots a histogram of the results.
800
600
number
400
200
0
130 140 150 160 170 180 190
critical frequency
NESTED LOOPS
For-end loops are often nested inside each other. For example, if a parts cabinet
was stocked with exactly four types of resistors, 10Ω, 22Ω, 47Ω, 51Ω, find all pos-
sible combinations of these types:
function FindResistors()
% FindResistors finds all combos of 2 resistors
% given 4 types
vr = [10 22 47 51]; % 4 types of stocked resistors
for i1 = 1:4 % the first resistor index
R1 = vr(i1); % R1 is the first resistor value
for i2 = 1:4 % choose the second resistor index
R2 = vr(i2); % R2 is the second resistor value
fprintf('R1 = %g, R2 = %g\n’, R1, R2)
end
end
This code returns the following output:
R1 = 10, R2 = 10
R1 = 10, R2 = 22
R1 = 10, R2 = 47
R1 = 10, R2 = 51
R1 = 22, R2 = 10
PRACTICE PROBLEMS
Consider a program that searches for integer solutions for the sides of a right
triangle, known as Pythagorean triples, satisfying c = √a2 + b2 . The program
searches for integer hypotenuses as side a ranges from 1 to some given upper
bound N and as side b ranges from 1 to N.
RECALL
x is an integer only if x == floor(x)
PRACTICE PROBLEMS
Finding exact solutions, as was done in the previous section, is done by testing
with the == operator. Sometimes exact solutions do not exist, in which case one
must settle for finding the best solution. Finding this best solution requires keep-
ing track of the current best solution, and checking through every iteration to
see if the current computation is better. Error is often computed using code of
the form error = abs(currentComputation – desired) since it is
the absolute error that needs to be minimized.
% duplicate vR by multiples of 10 to create all
% standard value Rs
vR = [0 vR vR*10 vR*100 vR*1e3 vR*1e4 vR*1e5 1e6];
R1best = 0; % we haven’t yet found the best value of R1
R2best = 0; % we haven’t yet found the best value of R2
bestError = 1e12; % our initial error is huge
9. C
hange the above program to print out the closest value of
two standard-value resistors in parallel to a given desired
resistor. Test to find the nearest parallel combination of
standard resistor values to match R = 40.5 Ω. How close is it?
tic, toc
The commands tic, toc will time how long it takes matlab to execute the
commands that separate them. These commands must be either within a func-
tion or cut and pasted into the command window; otherwise, most of the delay
between the “tic” and the “toc” will be from your typing speed, not matlab’s cal-
culation speed limitations.
function calculationspeed
% find how long it takes to create two random 50x50
% matrices and multiply them together
tic
a = rand(50,50); % create two random 50x50 matrices
b = rand(50,50);
c = a*b; % multiply them together
toc
matlab then returns the following on my 2017-era computer:
Elapsed time is 0.278700 seconds.
The toc command will also return the elapsed time in seconds to a variable.
10. How quickly can matlab solve a set of 100 equations with
100 unknowns? This problem was described in Chapter 2,
but to avoid typing 10,000 test coefficients, create a random
problem. First create a 100 × 100 matrix of random numbers
and save in variable A using the command:
A = rand(100,100);
Then create a 100 × 1 column vector of random numbers
called b. Finally, time how long it takes to solve them using
the command:
V = A\b;
PRACTICE PROBLEMS
while-end Loop
The for-end command loops for a number of times that is known in advance,
unless a break statement ends it early. The while-end loop will loop until a
logical condition is true.
while(logical test statement)
program code to be run
end
It is less common than the for-end loop command, and like the for-end
loop command, can be exited early using the break statement. It can be used,
for instance, in simulations that iterate until an error is acceptably small.
function sum=WhileExample(x)
% WhileExample will loop until new additions are < x
PRACTICE PROBLEMS
Often a function will return a vector whose elements are calculated inside a loop.
In this case, the vector may be either initialized to the full size with a zeros()
command and then filled inside the loop or else grown to size inside the loop
with its length increasing with every loop. The former method is much more
efficient and is accomplished by reserving the required memory for the vector
before the loops begins with a command like this:
result = zeros(1,1000);
The latter less-efficient method is to grow the size of vector in the middle of the
loop, like this:
result = [newvalue result];
If the resulting vector size is known before the loop begins executing, as is often
the case, use the former method. Only if the resulting vector length is not known
in advance should the latter method be used.
DIGGING DEEPER
The reason why vectors should be initialized with some value
like zeros, rather than grown as needed, is because of the
way matlab grows vectors. If a vector needs to be grown to
accommodate a new value, for instance, to go from length
100 to length 101, matlab must first internally create an entirely new 101 length
vector, then copy the original 100 values over to it, then save the additional
single value, and then destroy the original length 100 vector. Compare this
with the faster alternative of preallocating memory for the final array once,
and then replacing the initialized values with the calculated values.
PRACTICE PROBLEMS
Looping Functions
for-end for i = 1:10, fprintf('Loop %g\n', i); end
break breaks out of a loop
while(condition)-end loop until the logical condition is met, then exit
Utility Functions
tic, toc prints elapsed time
tic, t=toc; saves elapsed time in seconds in variable t
disp()
Binary Functions
dec2bin(73) converts a base 10 value into base 2
bin2dec('101') converts a base 2 number (in quotes) into base 10
1. Write a matlab program that takes vector t, and returns a vector v, according
to the formula:
1+ t , t ≤ 0
v (t ) =
2e− t-1, t > 0
2. A compander is a device that passes audio signals from -1 V to 1 V without
change, but reduces the gain of higher magnitude signals, in part to
prevent very large transient (short length) signals from saturating the
system. You will learn more about companders in Communication courses.
An example of a compander is the rule:
1 1
vin − , −2 ≤ vin ≤ −1
2 2
v
vout = in , −1< vin < 1
1
vin + 1 , 1 ≤ v in ≤ 2
2 2
ote that the horizontal axis (the “x” axis) is vin and the vertical axis (the
N
“y” axis) is vout. Write a matlab program that takes a vector of values for vin
and returns the associated vout vector. It should have the following function
definition line:
function vout = problem02(vin)
Test the code by verifying that the command problem02([-2 0 2])
evaluates to [-1.5 0 1.5].
Check that the function works correctly. The following input should produce
the plot shown below:
[t,v] = problem03(21, 2, 10)
plot(t,v)
The function definition and the first few lines of the code should be:
function [x,y] = problem04(N, alpha)
x = 0:N;
for i = 1:N+1
curX = x(i); % current value of x
Check that the function works correctly. The input below should produce the
plot shown below:
[x,y] = problem04(100, 0.5)
plot(x,y)
5. I n the “Nested Loops” section on page 187, there is a code segment called
“FindResistors” that outputs all combinations of four resistors taken two at
a time. However, it does not recognize that R1 = 10, R2 = 22 is the same
combination as R1 = 22, R2 = 10. Modify the code to avoid listing duplicates
like these. Hint: change the start index of i2 from 1 to something else. This
requires some thought; it may help to find the pattern by crossing out the
repeats in the output table. It should have the following function definition
line:
function problem05()
Test the code by verifying in the command line that one can create an 8.5 Ω
resistor by placing a 1 Ω and a 7.5 Ω resistor in series, equivalently
[r1, r2, result] = problem06(8.5)
evaluates to
r1 = 1.0, r2 = 7.5, result = 8.5
Similarly verify that the best way to create a 2.555 Ω resistor is by placing a 4.7
and 5.6 Ω resistor in parallel, equivalently
[r1, r2, result] = problem06(2.555)
evaluates to
r1 = 4.7, r2 = 5.6, result = 2.5553
7. A
Pythagorian Triple, as previously discussed, is a rectangle in two
dimensions with integer sides and an integer diagonal. It must satisfy the
equation x2 + y2 = d2 (for example, 3, 4, and a diagonal of 5, since 32 + 42 = 52).
In three dimensions, this becomes a rectangular prism (a box) with three
integer sides and an integer diagonal connecting opposite corners. It must
satisfy the equation x2 + y2 + z2 = d2 (for example, 1, 2, 2, and a diagonal of 3,
since 12 + 22 + 22 = 32). Write a program to find one such set of four numbers,
in which each of the sides and diagonal are at least 5 and not more than 11.
Hint: Three sets of nested loops are needed, one for each variable x, y, and
z. It takes no arguments and returns four different scalars x, y, z, and d with
any single solution (there is more than one solution).
S ince both functions are defined in just one file, just provide the single
file called problem08 that houses both functions. Also provide the
histogram image in a separate Word file.
fc = 1
√ 2π R1R2C1C2
a. Write a function that computes fc given values of R1, R2, C1, and C2. Call
this problem09LP. To test it, verify that when called with two identi-
cal 10 kΩ resistors and two identical 1 μF capacitors, the cutoff frequen-
cy fc returned is 15.916 Hz.
b. Let the resistors be 10 kΩ with a 5% tolerance (meaning each could
be anywhere from 9.5 kΩ to 10.5 kΩ ) and the capacitors be 1 μF with a
10% tolerance. Write a second function called problem09 that calls
problem09LP from within the same file (i.e., the main function is named
problem09, and within that file the function problem09LP is defined;
see the section titled “Multiple Functions in One M-File” for further guid-
ance). The function problem09 takes a number N representing how
many times the circuit will be simulated using different component val-
ues. For each of the N trials, it generates random values for R1, R2, C1,
T he function declarations and some lines are shown below, where the
ellipsis (…) indicates one or more lines of unwritten code:
functionvFc = problem09(N)
vFc = zeros(1,N); % preallocate for speed
for i = 1 : N
…
function fc = problem09LP(R1,R2,C1,C2)
…
V1 = Vin R1
R1 + R2
R1 is given as follows:
a. Write a function that computes V1 given values of Vin, R1, and R2. Call this
function problem10Divider. To test it, verify that when called with
Vin = 10 V, R1 = 1 kΩ, and R2 = 10 kΩ, it returns a value of 0.9091 V.
b. Let Vin = 10 V exactly, R1 = 1 kΩ ± 5%, and R2 = 10 kΩ ± 5%. The 5%
resistor tolerance means the 1 kΩ could be anywhere from
1 kΩ - 5% = 0.95 kΩ to1 kΩ + 5% = 1.05 kΩ. Write a second function
T he function declarations and some lines are shown below, where the el-
lipsis (…) indicates one or more lines of unwritten code:
function v1 = problem10(N)
v1 = zeros(1,N); % preallocate for speed
for i = 1 : N
…
function V1 = problem10Divider(Vin, R1, R2)
…
11. A fault-tolerant computer has three redundant cores. Each core has a base
20% chance of failing. If any core fails, then recheck both the remaining
cores a second time to see if they fail—now they will fail with a 30%
likelihood. The fault-tolerant computer will fail if more than 1 core fails.
a. Write a function that computes whether, for a particular trial, the fault-
tolerant computer fails. Do this by generating a random value for each
core to determine if it fails. If any one core fails, then generate new
random values for each of the remaining cores to see if they fail. If they
do, the entire system fails and the function should return a 0; other-
wise the system works and the function returns a 1. Call this function
problem11Trial.
T he function declarations and some lines are shown below, where the el-
lipsis (…) indicates one or more lines of unwritten code:
function v = problem11(N)
v = zeros(1,N); % preallocate for speed
for i = 1 : N
…
function works = problem11Trial()
…
function v = problem12(N)
v = zeros(1,N); % preallocate for speed
for i = 1 : N
…
function tlow = problem12tlow(R1, R2, C)
…
a. Write a matlab function that takes argument N and returns 10,000 pairs
of points {t,y} that plot the function over the range −1 ≤ t ≤ 1. The first
few lines of the function definition (where an ellipsis … indicates more
code follows) are shown below:
function [t,y] = problem13(N)
t = linspace(-1,1,1e4);
y = zeros(1,1e4); % preallocate for speed
for i = 1:1e4
tCurrent = t(i);
for n = 1:N
b. Plot the result for N = 100. The plot should look jagged and self-similar
when zoomed in a little. matlab’s limited precision prevents making
N arbitrarily large, since the 7n term becomes large quickly, but in the
limit the graph would be jagged and self-similar, regardless of the zoom
level.
16. A Collatz Sequence refers to a sequence that begins with any positive
integer a1 and whose next value a2 is computed recursively as half of a1 if
that results in an integer, or else three times a1 plus one. Mathematically
stated, a Collatz Sequence appears as follows:
a_
n1, an even
an = 2
3an_1 +1, an odd
17. Use the results of the previous problem to write a function that
determines which starting number, from 1 to a given integer N, has the
longest Collatz Sequence. The function should return two numbers, the
starting integer and the length of the resulting sequence. For example,
if N = 5, then it should return the integers 3 and 8, since the Collatz
Sequence starting with 3 is 3, 10, 5, 16, 8, 4, 2, 1, and at length 8, it is
longer than the Collatz Sequences starting with any other number from
1 to 5. Hint: This function should call problem16(). The function
definition is as follows:
function [longestA, longestLength] = problem17(N)
18. Write a function that models the amount of money saved by an engineer.
The engineer earns E dollars at the start of every month, and automatically
deposits P percent of that into a savings account. The savings account earns
I interest monthly, which is deposited at the end of the month.
rite a function that returns how much is in the savings account at the end
W
of the month after M months. For example, if the engineer has a monthly
salary of $10,000 and saves 10% of that in a savings account earning 1%
monthly, E = 10,000, P = 10, and I = 1, and after the first month she will have
saved 10% of $10,000, which is $1,000, and earned 1% interest on it for a
total of $1,010. After the second month she will have deposited an additional
19. Modify the problem above so that at the end of every year, the engineer
receives a raise of R percent. Hint: Inside the monthly for loop, at the end,
check to see if the month is evenly-divisible by 12, and if so, modify her
salary. The function definition is as follows:
function saved = problem19(E,P,I,M,R)
To test it, after 10 years (120 months) of saving 10% with a starting monthly
salary of $10,000 in an account that earns 1% monthly, and earning a 5%
annual raise, problem19(10000,10,1,120, 5) should return $278,694.23
(or, 2.7869e+05 in matlab’s scientific notation. Use format bank to see the
answer to two decimal digits).
20. A square wave is applied to the circuit shown below that has a capacitor
value of 1/k.
1
The following piecewise-defined voltage v(t) is measured where V0 =
1 + ek
21. Repeat the calculations from Problem 20, but use k = 1/4. This demonstrates
how a simple circuit with a resistor and capacitor can turn a square wave
into a triangle wave.
26. Filtering (i.e., operating on) data is commonly used in Electrical Engineering,
as well as in other disciplines. Stock market analysis, for instance, may use
a 3-day moving average filter to look for trends while ignoring short-term
transients. A 3-day moving average takes a vector of daily prices for a stock
and returns a vector of the same length, representing the same time span,
whose corresponding values are the average of three days’ worth of current
and previous data (where possible). For example, the output vector’s value
at index 20 is the average of the input vector’s values at 18, 19, and 20.
There are two cases where this is impossible to do: neither of the first two
values in the output vector can be calculated this way because there does
not exist enough data in the input vector to do so. The second value of the
output vector can only be the average of the first two values of the input
vector, since one cannot go back an additional index in the input vector (it
27. Generalize the function that solves the previous problem so that the
function is a moving average filter of length M, where M = 3 in the previous
problem. Hint: The mean(v) command calculates the average of vector v.
The first few lines of the function are shown below:
function out = problem27(in, M)
N = length(in);
out = zeros(1,N); % preallocate vector
To test it, note that problem27([46 48 50],2) returns [46 47 49].
28. The built-in function exp(x) computes ex, but it could also be computed
in the limit as N grows large using the formula shown below:
N
xn
e =1+
x
where n! means the product of 1 × 2 × 3 × 4 ×… × n.
n=1 n!
1001101
31. Write a function that takes a number in (typical) decimal form and returns
three strings: the string representation of the number in binary, in decimal,
and in hexadecimal (base 16). The function definition is as follows:
function[bin, dec, hex] = problem31(in)
To test it, note that
[bin, dec, hex] = problem31(11)
should return
bin = '1011'
dec = '11'
hex = 'B'
32. Fourier series analysis is an important technique from the signal processing
subdiscipline of electrical engineering. It involves the fact that any periodic
waveform can be broken up into a sum of sinusoids. It sounds impossible
that a sharp-edged function like a square wave could be composed of
49
sin ( kt)
f=
k = 1 , 3 , 5 , ... k
In words, this means to first create a time vector t, and then initialize the
result vector f to be filled with a vector of zeros that is the same size as
the t vector. Next, create a for loop using loop variable k that starts at
1 and increments in steps of 2 so it becomes every odd number up to
49. For every iteration of the loop, add the vector sin(k t)/k to f. This is a
vector because t is a vector. The function returns f, but check your work
by embedding a plot (t,f) at the end of your code. It should look
similar to a squarewave. As the upper limit of the sum, 49, is increased the
function will appear progressively more similar to an ideal square wave.
When the program is run, besides returning the vector f, it should also
display the plot. Place this plot in a Word document.
33. Challenging!: You want to create a 72 Ω resistor, but that is not a standard
value. One way to build it is with a 33 and 39 Ω in series. Another way is
with a 75 and 1800 Ω in parallel. Numerically, both these options work
out to the same 72 Ω resistor. If you do a Monte Carlo analysis of the two
options with 10,000 simulations, do the two options have the same spread
of tolerances if they are all made with 5% resistors? For this problem, the
function should create the two histograms of data, labeled to show which is
the series and which is the parallel solution. These plots should be placed in
a Word document with additional text indicating your evaluation of which
is the better method or if both are equally preferable.
After completing this chapter, you will be able to use LTspice to do the following:
CIRCUIT SIMULATION
General circuit simulators calculate the voltages and currents in arbitrary circuits.
They have been in existence since the early 1960s, encouraged by increasingly
complex circuit designs and initially funded by the US Department of Defense.
An undergraduate class project in Berkeley spurred some of the first precursors
to the open-source program we now know as SPICE, the Simulation Program
with Integrated Circuit Emphasis. The first complete version was authored by
Laurence Nagel in 1973, and SPICE has since evolved to become the de facto
open-source standard for all circuit simulation packages.
UTILITY
There are often two stages involved when solving real-world engineering problems:
design and validation. In the design phase, the engineer uses the problem speci-
fication to create the schematic using techniques taught in circuit and logic design
courses. The design phase cannot be aided by circuit simulation, although there
are other packages that can assist with this phase, such as filter design programs.
The validation phase confirms that the circuit created in the design phase works
as intended. Circuit simulators assist this phase by testing how the design per-
forms in both ideal and nonideal conditions, and they can evaluate performance
given a range of component tolerances, temperatures, and operating conditions.
When the installation is complete, the program will automatically load and show
the screen below:
STEPS IN SIMULATING
This textbook describes the following three steps in circuit simulation in detail:
1. Draw the schematic (i.e., schematic capture). Three different types of
entities must be defined in this stage:
A. Components, such as voltage and current sources, resistors, capacitors.
B. Ground.
C. Wires connecting the above elements.
SCHEMATIC EDITOR
Circuit simulation begins with schematic capture, which means creating a sche-
matic diagram in the schematic editor. A schematic is composed of components
(such as voltage and current sources, resistors, capacitors, inductors, diodes, tran-
sistors, and integrated circuits), at least one ground symbol, and wires connecting
the components and ground. Every component has two pieces of associated data:
its name, called its reference designator, and data describing its value. For exam-
ple, a particular resistor may be named with a reference designator R11 and have a
value of 4.3 kΩ, or a voltage source may be called V1 and have a value of 12 V.
Once loaded, the program will appear as shown on page 229. The grayed-out
logo in the center of the screen indicates that there is no current schematic. To
create one, choose File → New Schematic from the menu. The logo will disap-
pear, and the program’s title bar will show “Draft1.asc” to indicate that a new
schematic has been created with the default name. Change the name to “Sche-
matic1” by using File → Save As and notice the change in the title bar text.
Note the folder in which the library is defined, highlighted with a red ellipse in
the figure above. If the component dialog does not show components and com-
ponent folders, beginning with the [Comparators] folder, it is because the library
folder is pointing to the wrong location. Change it to the C:\Users\YourUser-
Name\Documents\LTspiceXVII\lib\sym folder using the Top Directory dropdown
selector and the Move Up Folder selector highlighted above.
To create a voltage source, select the component option using the button on
the main toolbar. The component dialog box should appear as shown above, still
set to the correct library location selected in the above step. Move the horizontal
scrollbar until “voltage” is highlighted. Select it, click to place it in the schematic,
and press the Escape key to escape from voltage source placing mode.
The LTspice voltage and current sources are very flexible; they can represent con-
stant-voltage or current sources, a square wave, a sinusoidal wave, or a number
of other commonly encountered waveform types. By default, it is a DC (constant)
source. To select a different waveform type, right-click the symbol (not the text)
and choose the “Advanced” button.
To change the designator ID of the source, right-click the text surrounding the
source. Typical names for voltage sources are V1, V2, etc., and I1, I2, etc., for cur-
rent sources.
Wires are drawn after selecting the wire tool, . Unwired connection points on
components appear as open squares; once connected with a wire, the square
disappears. The ground symbol is placed after selecting the ground tool, .
Make certain the open square on top of the ground disappears after connecting
it to the rest of the schematic with a wire. If this is not done, or if the ground is
not placed, the simulation will fail and report the warning, “This circuit does not
have a conduction path to ground.”
Future courses will likely introduce myriad new components, called integrated
circuits (the “IC” in SPICE). These can be found from the component dialog box by
opening up the folder of the IC category, and they include components such as
comparators and opamps. Sometimes generic components will be available; an
example of this is the “opamp” available in the “Opamps” library, which is meant
to represent a generic, somewhat-idealized opamp.
There are three commonly used SPICE analysis types at the undergraduate level:
DC Operating Point, Transient, and AC Sweep.
DC Operating Point: This is a complicated name for a simple concept. Use this
analysis type if the circuit has only unchanging sources, meaning constant-volt-
age and constant-current sources. In this case, all voltages and currents in the
circuit will also be constant, and would be measured in a real-world circuit using
a digital multimeter. There are no options for this simulation, and the results are
viewed by hovering the cursor over the wire or component of interest.
Transient Analysis: This is the analysis type to use if the circuit has changing
voltages and currents. Examples include circuits whose sources step from one
voltage to another, or are defined to be a square wave, or if the circuit oscillates.
The real-world circuit would require an oscilloscope to view how the circuit volt-
ages and currents change in time; the simulated results are viewed by clicking
the wire or component of interest after simulation to show their voltages on a
simulated oscilloscope.
DC SIMULATION WALKTHROUGH
The second and third phases of circuit simulation, defining the analysis type and
viewing the results, are best taught by example. The first of the three main types
of circuit analysis this chapter covers is DC simulation, and it will be taught by
completing an analysis of the circuit shown below:
PRACTICE PROBLEMS
3. S imulate the following circuit you built in Practice Problem 2,
and find the voltage across the 4 Ω resistor.
5. H
ow long will 8 1.5 V AA batteries power the circuit above if a
single AA battery holds about 10 kJ of energy? Hint: solve the
energy
power = time equation given above for time. ©
Schematic
Pin numbering
The design equations for this circuit are:
LED blinks on for 0.693*R2*C seconds
TRANSIENT SIMULATION
The second of the three types of circuit analysis this chapter describes is tran-
sient analysis. It will be taught by completing an analysis of the circuit shown
below (L). Note that although similar, this is not the solution to the Practice Prob-
lem. Follow through the steps that follow to gain a solid working knowledge of
transient circuit analysis. When the schematic capture is complete, it should look
as shown below (R). LTspice fixes the location of the IC pins in the same positions
as on the physical chip. Although this makes wiring up a physical circuit from an
LTspice schematic easier, it makes the schematic more difficult to read.
Wire It Up
• Use the tool to wire the circuit together.
• hoose “OK” and place the “.tran 0.5” text on a blank area of the schematic.
C
• Select Simulate → Run from the window or choose the button. The
following split schematic/analysis window will appear.
• osition the cursor over a wire in the schematic in which you want to
P
see an oscilloscope-style plot of the voltage versus time. In the example
above, the cursor is hovering over the wire that is attached to pin 3,
OUT. The cursor changes to resemble a red oscilloscope probe.
• Click on the probe to display the corresponding voltage waveform.
PRACTICE PROBLEMS
7. M
odify the above walkthrough to print one second’s worth
of data. Record a screen grab of the analysis window using
the Snip & Sketch Tool (if on Windows) or Command+Shift+4
(if on a Mac).
AC SWEEP SIMULATION
The last of the three types of circuit analysis this chapter describes is AC sweep
analysis, and it will be taught by completing an analysis of the circuit shown
below on the left (note that although similar, this is not the solution to the Prac-
tice Problem). Follow the steps below to gain a solid working knowledge of AC
sweep analysis. When the schematic capture is complete, it should look as below
on the right. Notice that because ground is defined, there is no need to bring the
lower wire out from the schematic to define Vout between two points; it is now
the single point to the right of the opamp.
Wire It Up
• Use the tool to wire the circuit together.
• osition the cursor over a schematic wire of whose voltage you want to
P
examine a Bode-style plot of the voltage versus frequency. The above
example highlights the cursor hovering over the wire that is exiting out
of the opamp. The cursor changes to resemble a red probe.
• Click on the probe to display the corresponding voltage.
PRACTICE PROBLEMS
9. M
odify above walkthrough to use 20 k resistors, but the same
value of capacitors. Analyze the performance of the filter over
the same 1 Hz to 10 kHz range. Record a screen grab of the
analysis window using the Snip & Sketch Tool using Windows
or Command+Shift+4 on a Mac. Does the cutoff frequency
increase or decrease as resistor values are increased?
The opamp schematic is functional, but looks messy because of the 5V sources
providing power to the opamps. If we defined a symbol like +5V to be 5 V and
−5V
another to be –5 V, then we could significantly neaten the schematic while
making the intent clearer. These symbols are examples of nets, as illustrated in
the following schematic:
The circuit on the right is functionally the same as the previously analyzed circuit
on the left. The two voltage sources that are apparently unconnected define two
nets called +5 V and 5 V, which are used to power the opamp on the right. It also
uses multiple ground net symbols to simplify the schematic further. Practicing
engineers much prefer this to the schematic on the left.
LTspice permits the definition of nets using the tool. As an example of using it
to simplify the previous schematic, first create the following schematic capture:
Wire them up as shown below. Now every time a +5 V net symbol is used, it is
functionally identical to being wired to a +5 V voltage source whose more nega-
tive end is wired to ground. This is perhaps only marginally neater in this sin-
gle-opamp example, but becomes far neater in more complex circuits that use
multiple opamps.
Place ground
Zoom Tools
Zoom in, pan, zoom out, and zoom to full circuit
Schematic Editing Commands
Delete tool
Move tool
Undo tool
Analysis Commands
Simulation → Edit Simulation Choose the simulation type
• DC op pnt Voltages unchanging
(after selecting Simulation → Edit Simulation)
• Transient Voltages change with time
(after selecting Simulation → Edit)
• AC Sweep Changes input sinusoidal frequency
(after selecting Simulation → Edit)
Run the simulation
View Results
DC Hover mouse over schematic for voltage, current, power
Transient Click wire to add to oscilloscope display
AC Sweep Click wire to add to Bode plot
1. U
se LTspice to find the voltage across the 10 Ω resistor in the following
circuit. (Hint: do not forget to assign a ground node in LTspice!)
2. T he circuit above is powered by 2 AA batteries. How long will the circuit last
if a single AA battery holds 10 kJ of energy?
3. Find the voltage across the current source in the circuit shown below. The
current source is called “Current” and is found in the same library that holds
the “Voltage” source. Print the LTspice schematic showing the voltage at the
top of the current source.
4. F ind the current through the voltage source of the three-dimensional cube
of 1kΩ resistors shown below. Print the LTspice schematic showing the
current through the voltage source. Some versions of LTspice show current
in wire after simulation by hovering over it; some only show the currents
in the postsimulation screen. Take a screenshot of the current through the
voltage source. Do not be concerned if the current is positive or negative;
the sign indicates only the direction of flow.
5. T he duty cycle of a square wave is the ratio of the time the cycle is spent
“on” divided by the total length of time of each period. For instance, if
the “on” time is 1 second, and the “off” time is 3 seconds, then the total
9. You are an Electrical Engineer working for a company that designs natural
gas powered electrical power plants. One of the newly hired members on
your team is upset that the company is not spending more time examining
the profitability of generators powered by renewable energy sources, such as
wind and solar. The issue was already examined in a lengthy and expensive
You feel torn between your duties to your coworkers, your employer, your
family, and the military personnel who will be relying on this technology.
You do not know if your concerns are valid without months of additional
simulations. What do you do?
A C
abs 51 C xii
acos 17 C# xiii
acosd 18 C++ xiii
AC sweep analysis 238, 251 calculator 3, 62
addition ceil 69
matrix 64 charge 5, 11
scalars 3 Circuits course 37, 92
vector 53 clear 136
all 152 colon 40
alpha 113 color code 163
AND gate 150, 200 comments 141
angle 51 Communications course 205
any 152 compander 205
arguments 136 complex exponential 50, 52
asin 17 complex numbers 49
asind 18 conditional branching 154
astable multivibrator 245 cos 17
atan 17 cosd 18
atand 18 current 5, 11
AutoCAD xiv
AWG 160 D
axis 87 DC operating point analysis
axis limits 86 237, 238
B dec2bin 201
delta 113
bar plot 104 design 228
beta 113 digital logic 150
bin2dec 201 disp 178
binary math 200 division
bit 30 matrix 64
Bode plot 90, 145 scalars 3
Boolean math 200 vector 53
break 195 DMM 19, 42
byte 30 buying 48
263
doc 24 I
doctoral degree 147
i 14, 49
E IEEE 7
Code of Ethics 118
EE careers 26 if 154
else 156 imag 51
elseif 157 imaginary. See imag
embedded m-files 196 implied multiplication 10
end 45, 154 indexing 45, 60
energy 242 industry 165
engineering notation 162 Inventor xiv
eta 113 isequal 149
ethics 118, 243
Euler 49 J
exp 16, 53
exponentials 16 j 14, 49
Java xiii
F JavaScript xiii
FE. See Fundamentals of Engineering K
fellowship 148
floor 38 kilo 162
flowchart 154 L
for 178
format 14, 114 lambda 113
Fourier series 224 legend 96
fprintf 159 length 44
function 131 license 99
Fundamentals of Engineering 202 lifelong learning 257
line plot 81
G linspace 40
gamma 113 load 25
gca 110 log 16
gcf 110 log10, 16
get 110 logarithmic axis 89
Giga 162 logarithms 16
graduate school 147, 165 logical expression 149
Greek symbols 113 logical math 200
grid 88 logical operator 150, 151
ground 230 loglog 89, 119
logspace 40
H low pass filter 92, 144, 250
LTspice 228
handle graphics 109
help 23, 142 M
histogram 185
history 25 magnitude 51
hold 102 masters degree 147
264
MathCAD xiv oscillator 245
MATLAB xii oscilloscope 88
command window 2
P
directory control 2, 129
layout control 2 P.E. See Professional Engineer
tab control 2 parentheses 10
workspace window 9 phi 113
matrix 57 pi 14, 113
build from vectors 59 calculate 224
dimensions 57 pico 162
explicitly define 58 plot 81
fill with duplicate values 58 labels 85
indexing 60 line colors 82
removing elements 61 line styles 83
size 63 line widths 83
transpose 63 titles 85
Mega 162 plot editor 108
memory pre-allocation 198 polar 50
mesh analysis 65 post-graduation careers 147
meshgrid 115 power 16, 242
micro 113, 162 pre-allocation 198
milli 162 prime search 195
Monte Carlo 184 Professional Engineer 99
mu 113 program comments 141
multiple line plots 94 Pythagorean triples 189
multiplication Python xiii
implied 10
matrix 64 R
scalars 3 rand 20, 41, 59
vector 53 random. See rand
Multisim xiv real 51
N rectangular 50
reference designator 232
nano 162 relational expression 149
nested loops 187 resistance 11, 42
nets 255 resistor 12, 43, 235
nodal analysis 65 color code 163
NOT gate 150, 200 in series and parallel 56
NSPE Code of Ethics 244 standard values 43
O round 38
S
Ohm’s Law 13
omega 113 save 24
ones 39, 58 scatter plot 97
operational amplifier 236, 249 schematic capture 232
OrCAD 228 schematic editor 232
OR gate 150, 200 scientific notation 15
265
script 100, 129 title 85
semicolon 21 toc 193
semilogx 89, 119 transfer function 92
semilogy 89, 119 transpose 63
set 111 trigonometric functions 17, 53
shading 116
V
shortcuts 25
sigma 113 validation 228
Signals and Systems course 37, 120 variables 7
simultaneous equations 66 vector 38
sin 17 define explicitly 39
sinc 155 end 45
sind 18 fill with duplicate values 39
size 63 fill with exponentially-spaced values 40
Solidworks xiv fill with linearly-spaced values 40
sort 146 fill with random values 41
Spice xii 227 indexing 45
sprintf 158 inserting elements 47
sqrt 16, 53 length 44
str2num 55 logspace 40
strings 54, 158 removing elements 46
subplot 106 Verilog xiv
subscripts 114 VHDL xiii
subtraction voltage 11
matrix 64 voltage divider 67
scalars 3
vector 53 W
superscripts 114 while loop 197
surf 116 wire sizing 160
T work 242
tan 17 X
tand 18 xi 113
tau 113 xlabel 85
Tera 162
text 112 Y
text on plots 112
theta 113 ylabel 85
three-dimensional plots 115 Z
tic 193
timing 193 zeros 39, 58
266