Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4...

52
R1 2K R2 2K R3 101K R4 100K C1 .01μ C2 .01μ V1 5 Q1 2N3904 Q2 2N3904 .tran 25m startup This example schematic is supplied for informational/educational purposes only. Computer Tools for Electrical Engineers EE120 Virginia Military Institute COL James C. Squire, P.E., Ph.D 1 August 2016

Transcript of Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4...

Page 1: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

R1

2K R2

2K

R3

101KR4

100KC1

.01µ

C2

.01µ

V1

5

Q1

2N3904

Q2

2N3904

.tran 25m startupThis example schematic is supplied for informational/educational purposes only.

0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms

Computer Tools for Electrical Engineers EE120

Virginia Military Institute

COL James C. Squire, P.E., Ph.D 1 August 2016

Page 2: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers
Page 3: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page i

Forward

Welcome Class of 2020, as you embark on your journey in ECE! You did not choose VMI because you wanted an easy college experience, and you did not choose ECE because you wanted an easy major. Many of you came searching for a challenge that fit well with your natural bent towards math and science. Some have prior experience in First Robotics, Lego League, or in a high school electronics course. Some have never been exposed to engineering as a career before a guidance counselor suggested it. Others have always known engineering was right for you from the first time you took apart (and possibly put back together) a household gizmo, or saved spare parts taken from broken toys. While most see engineering as a way to help solve society’s problems using technology, all of you will soon appreciate our department as an extended family filled with others who share their odd sense of Monty-Pythonesque humor, who have actually read their calculator manual, and who tend to notice the technical faults in science fiction movies. As you go through our curriculum, you will find the way you think about problems will change – your analysis will become clearer, your ability to discard confounding variables will sharpen, and your ability to construct and test models of the processes you are interested in will improve. This will be true whether the problem is how to build an improved voltage amplifier, how to increase morale of the junior engineers in your unit, or how to grow a company in the face of fierce international competition. It is not surprising our graduates perform well in engineering, leadership, and business roles upon graduation, and many go onto diverse careers in law, medicine, and the military. Indeed, Forbes Magazine notes that engineering and computer science majors were found to have greater post-graduation salaries than any other major1. This advantage does not attenuate in time; engineering has long been ranked as the most common undergraduate degree among Fortune 500 CEOs2, more than business or economics majors. But although your degree will give you many benefits when you graduate, for the next four years you are part of our department family. We expect you to be responsible, respectful, and a team player, and you should expect the same from your classmates, upperclass ECE majors, and professors. Hold your classmates accountable when you see them acting discourteously or thoughtlessly. If you see something wrong, fix it if you can, or tell your dyke, academic advisor, or any department professor if you can’t. These habits will make you successful as a cadet, successful as an alumnus, and successful in whatever career you ultimately choose. Welcome to VMI and ECE, COL Squire, 1 Aug 2016 1 “The College Majors with the Highest Starting Salaries,” Forbes Magazine, July 2, 2015. 2 “Why Engineers Make Great CEOs,” Forbes Magazine, May 29, 2014.

Page 4: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page ii

Page 5: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page iii

Table of Contents

Introduction to Computer Tools for ECE Majors .................................... 1

Module 1: Introduction to Matlab ........................................................... 5

Module 2: Matlab as a calculator ......................................................... 25

Module 3: Plotting with Matlab ............................................................ 28

Module 4: Introduction to Matlab programming ................................... 30

Module 5: Programming – Looping ..................................................... 32

Module 6: Circuit simulation using Spice ............................................. 33

Module 7: Putting it into practice ......................................................... 34

Technical Tips and Problems

Common types of ECE software ........................................................... 1

Charge and current ............................................................................... 8

Voltage, current, charge, and resistance ............................................. 12

Ohm’s Law .......................................................................................... 12

Using a DMM to measure voltage ....................................................... 15

2a Types of resistors ............................................................................. ?

2a Using a DMM to measure resistance................................................ ?

2a Resistors in series and parallel......................................................... ?

2b Voltage dividers ............................................................................... ?

2b Mesh and nodal analysis concept .................................................... ?

3a Oscilloscopes and plots.................................................................... ?

3b Lowpass filters ................................................................................. ?

3b Bode plot style ................................................................................. ?

3b Standard resistor values................................................................... ?

3b Common Greek symbols used in ECE ............................................. ?

4a Creating good-looking plots .............................................................. ?

4b Engineering notation ........................................................................ ?

4b Wire sizing ....................................................................................... ?

5a Monte Carlo analysis ........................................................................ ?

5b Phasor analysis ................................................................................ ?

5b Binary math ...................................................................................... ?

6a What is ground? ............................................................................... ?

Page 6: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page iv

6a Power and energy (work) ................................................................. ?

6a Battery capacity ............................................................................... ?

6b 555 Timer ......................................................................................... ?

7a Capacitors ........................................................................................ ?

Professional (Career) Tips

Use a weekly calendar .......................................................................... 9

Goal-setting: find your voice ................................................................ 21

2a Buying a DMM ................................................................................. ?

2b Buying a calculator ........................................................................... ?

3a Where to study ................................................................................. ?

3b Ethics 1 ........................................................................................... ?

4a Overwhelmed? ................................................................................. ?

4b Efficient email handling .................................................................... ?

5a Post graduation opportunities ........................................................... ?

5b IEEE, ABET, EIT, PE ....................................................................... ?

6a Ethics 2 ............................................................................................ ?

6b Handing disillusionment ................................................................... ?

7a Stress-busters .................................................................................. ?

Page 7: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 1

Introduction to Computer Tools for ECE Majors

Purpose of this manual

I wrote this Computer Tools manual because I could not find an "ideal" laboratory manual in the roughly twenty introductions to Matlab and introductions to Spice currently published designed specifically for electrical engineering students. Many read like user manuals: “this key does this, this command that”, without much attempt at connecting to the underlying principles of electrical engineering. Some were very abstract – wonderful for those looking to understand the heart of procedural programming, but completely inappropriate as a freshman introduction. A few are excellent introductions to general engineering principles, but lack focus on the needs of specific majors. What is needed is an overview of Matlab and Spice as they relate to electrical engineering, accessible to someone without a background in programming or circuit analysis, and that introduces general programming and analysis concepts while solidly grounded in both the context and needs of a single-semester electrical engineering course. This is unapologetically a text that supports an electrical engineering course first – it omits concepts like data structures that would be critically important to a Computer Science student, and includes reviews of specialized mathematics like complex phasor analysis that are central to frequency-domain analysis but of less common use in non-EE fields. It provides an overview of the computationally-intensive methods used in Circuit Analysis, Electronics, Signals & Systems, Controls, and Digital Signal Processing. It touches on some ideas from the digital courses as well, but does not touch on HDL modeling of general digital systems – that deserves (and gets) a course to itself! In short, this text supports a course that is as much a general introduction to the analog half of electrical engineering as a course teaching how to use the specific programming packages of Matlab and PSpice.

Software commonly used in ECE

There are a number of software packages commonly used in Electrical and Computer Engineering, including Matlab, Spice, C, C++, VHDL, Python, Java, C#, JavaScript, , Multisim, Verilog, and others. You will learn about the first two in this course, and the first five as you progress through the VMI ECE curriculum. Others you may or may not learn depending on your elective choices and independent studies.

Core software packages you will learn at VMI

Matlab: This is the lingua franca of ECE, Aeronautics, and Bioengineering majors, and is becoming increasingly common in Mechanical Engineering as well. Matlab is a calculator-on-steroids, a

Page 8: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 2

graphing package with vastly more customizable results than Excel, and a general programming language. We will explore all these uses in this course. It works with numbers principally, and is not an algebraic solver like Wolfram Alpha or Wolfram Mathematica.

Spice: This is a circuit simulator capable of simulating almost any analog or digital circuit. It lets the user build the circuit graphically, and then probe it to read voltages and currents. There are many variants of Spice; in this course we will be using a free one called LTSpice, published by Linear Technologies here: http://www.linear.com/designtools/software/.

C: The oldest of the programming languages you will study at VMI, C has a simple syntax that is well-suited for use in embedded systems (miniaturized computers-on-a-chip) that you will use in the Microcontrollers class. It is very closely related to the language used to program Arduino microcontrollers. Despite its ubiquity in miniaturized embedded systems, you won’t find it used in full-sized PC programs because it is not as well-suited to make complex applications as modern languages that support object-oriented behavior.

C++: This language, pronounced “Cee-plus-plus”, is one of the most common languages used to develop programs that run on personal computers and the web. Unlike Matlab and Python, it can run directly from the operating system as a standalone program (Matlab and Python programs must run from within a Matlab or Python shell that must first be launched). It is a superset of C that adds object-oriented behavior.

VHDL: This is a specialized programming language used to program a specialized type of integrated circuit called a Field Programmable Gate Array (FPGA). These chips don’t execute code in a typical fashion; instead they can run many thousands of processes at the same time, and require a specialized language to do so. VHDL is slightly more common among defense contractors than its major competitor, Verilog.

Other common software packages

Python: This relatively new language is similar to an open-source version of Matlab. It is becoming increasingly common in the hobbyist world since it does not require an expensive Matlab license, but is not yet as common as Matlab in industry and academia.

Java: This language is popular because it is multi-platform. Like C++ it is object-oriented and creates stand-alone programs, and (in my opinion) has a slightly cleaner syntax than C++. It is very common but its overall use is slowly declining.

JavaScript: Despite its name, JavaScript has almost nothing in common with Java. This language has been growing in popularity since it became an embedded part of HTML (which is also why the use of Java is declining) and is most commonly used embedded within the html of web pages.

C#: This is a modern object-oriented programming language, similar in syntax to C++ but cleaner like Java. It has become more popular than Java to create windows-based programs that run on PCs and the web, but it is tied to the Microsoft operating system.

Multisim: This is another popular circuit simulator, similar to SPICE, currently more popular among hobbyists but gaining traction among industry professionals.

Verilog: Like VHDL, this is another language used to program FPGAs. Verilog is more common among non-defense contractors in the United States, and the language looks more like C.

MathCAD: This is a cross between a spreadsheet and a higher-mathematics package like Matlab. It is faster to learn, but has less programming power. It is more common in Civil Engineering.

Page 9: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 3

AutoCAD, Solidworks, and Inventor: These are solid-modeling programs, designed to create virtual models of two or three-dimensional structures. AutoCAD is very commonly used by Civil Engineers; Mechanical Engineers generally prefer SolidWorks or Inventor. Solid modeling is not a standard skill among ECE majors, but if you are interested in learning about it, take COL Squire’s EE455 Electro-Mechanical Methods elective.

Why this course concentrates on Matlab and Spice

While it would be wonderful to have every student finish their first semester with a working knowledge of each of these programs, we concentrate in this course on Matlab and Spice because:

1) There just is not enough time to cover all the packages!

2) Many will not make sense until you take more advanced ECE courses. VHDL and Verilog, for example, first require understanding of state machines and combinatorial logic, topics you will learn next semester in Introduction to Digital Logic, EE 128.

3) You will be able to learn new programming languages better once you have had a chance to apply them in the context of other ECE courses.

4) You will be required to use these two languages in future courses, such as Circuits I, EE122, that you’ll take next semester.

Page 10: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 4

Conventions in this manual

Each Module has two types of problems, Class Problems and Lab Problems. The Class Problems are designed to check general comprehension, do not requires extensive thought, and will be completed during class during the allotted problem-solving time (or even before class begins if you choose) and turned in at the end of class. They will, in part, determine your class participation grade. At the end of each module are a series of more difficult Lab Problems that will challenge you to implement the new material you have learned in the module in new ways.

Boxed items like this serve to highlight several different types of material including: 1) Particularly important ideas, like the final results of lengthy derivations or rare formulae

worthy of memorization 2) Class Problems that should be done as you read the material (most students will not

understand the readings unless they do the class problems as they are encountered)

Shaded callouts like this are not essential to the course, but can help in several ways. They include 1) Math Review: A review of math skills you learned in high school but may have forgotten 2) Digging Deeper: An optional discussion of an interesting topic in greater depth 3) Pro Tips: Advice to help you be a more effective student and better engineer

Make it better

Although I worked every problem in these labs there are still likely to be mistakes, misspellings, and areas that could be written more clearly. I welcome all your comments that will help make this laboratory manual a useful reference for the rest of your engineering careers. Please send them to [email protected].

Class Problems

1) What two software packages will you learn about in this course?

2) Name two languages commonly used in Electrical and Computer Engineering not taught in this course but that you will learn in your VMI ECE career, and describe how they are used.

3) This course will give you an overview of computationally-intensive methods used in which of these advanced ECE courses? Circuit Analysis, Semiconductors, Signals & Systems, Digital Signal Processing, Microcontrollers, C Programming, Electronics.

4) Given a choice between using C or C# to write a Windows program that would run on a PC, which would you use?

5) What software package would you use to write a program that runs on Linux and Windows: Java, or C#?

6) If you wanted to learn to make prototypes using the ECE rapid-prototyping machine (also known as a solid printer), would you model them in SolidWorks or AutoCAD if you were planning on sharing the work with Mechanical Engineering students?

Page 11: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 5

Module 1 – Introduction to Matlab

Objectives

When you complete this module you will be able to:

Start Matlab

Change its working directory to your network directory

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 Word

Use keyboard shortcuts like the arrow keys

How to optionally obtain and install Matlab

Matlab is available on the desktop of every lab computer in the Department of Electrical and Computer Engineering, so you do not need to install it on your personal laptop. In fact, I encourage you to use it in the department computer laboratories, like in NEB 404, 426, and 428 so you can work with the other ECE majors. However, if you want a personal copy, we have a campus-wide licensing agreement and you can take your laptop to the Barracks Help Desk (inside the Barracks Study Room and across from the VMI Post Office, open weekdays 0700-1600) and ask to have it installed it for free. This is a remarkable deal VMI has worked out; I had to purchase a private copy for my consulting work, identical to the ones at VMI except adding two things: permission to be used for private consulting work, and a $2,500 price tag.

Matlab, toolboxes, Simulink, and blocksets

If you do decide to install a VMI-licensed copy on your laptop, be aware that Matlab is actually a family of products that currently includes over 30 add-ons called “toolboxes”, a separate simulation program called “Simulink” and over a dozen add-ons to Simulink called “blocksets”. VMI has licenses to use all of them. Ask the helpdesk not to install anything other than Matlab until you have finished this class, otherwise it will swell the size of your installation and clutter your search for embedded help by over a factor of ten, effectively hiding the information you want to find in unrelated hits.

Page 12: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 6

Starting Matlab and the Workspace

1. Once you have located a lab computer, or installed it on your laptop, double-click its icon to run it. This may take a minute, especially if the installation includes many toolboxes or if this is the first time you are running it. Matlab will open its standard workspace as shown below.

The tab control The layout control

Matlab is composed of several controls and windows. The most important window is the center “command” window, into which you enter all your Matlab commands.

If the Matlab environment looks substantially different than the image above, make sure the tab control in the upper left is set to “HOME” and choose “DEFAULT” from the dropdown 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 plotting or filter design, that tend to be more cumbersome to use than learning the direct syntax, as we will in this course. 2. Next, create a data folder and make Matlab’s current working directory. The current working

directory is the directory in which Matlab expects to find the user’s data and programs.

a) Locate the directory control in the toolbar at the top of the Matlab main window.

b) Navigate to your personal directory on the network. This will be on the M drive.

c) Inside your personal directory, create a new subfolder called EE120 (don’t use a space).

d) Inside that folder, create a subdirectory called Module1 (with no space).

e) Note that the Current Directory type-in box in the toolbar now points to your Module1 working directory.

The directory window

List of currently-defined variables

The directory control

The command window

Page 13: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 7

Using Matlab as a calculator

At this point, type the following commands in the command window and observe what they do. Press “Enter” after each line. The Matlab prompt is ≫ and should not be typed:

≫ 2 / 5

≫ 3 + (4*9)^20 note that large numbers like 2∙1034, Matlab represents as 2e+34 ≫ x = 5

≫ x + 32

≫ x = 2

≫ y = x + 1

≫ sqrt(16)

≫ sqrt(-25)

Matlab can be used as an expensive calculator, and recognizes the following basic commands: + - * / ^ () sqrt(). Like in many programming languages, multiplication, division, and powers are represented by *, /, and ^. It uses the standard order of operator precedence to evaluate expressions, so 1 + 3 ^ 2 is the same as 1 + (3^2) = 10, not (1+3) ^ 2 = 16. When in doubt, use parentheses to be clear. Notice that if you don’t 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

yields 0.5 It is like your TI calculator from high school in several ways:

1. It only operates on the current line. When you changed the value of x to 2 above, unlike a spreadsheet but like your calculator it didn’t change previous calculations involving x, but only changes current and future calculations.

2. When there are variables involved (like x and y in this example) and an equals sign, Matlab first evaluates the statement to the right of the equals sign, and then sets the variable to that number.

It is unlike your TI calculator in other ways, however, and these may confuse you at first:

1. Matlab cannot perform symbolic algebra. Unlike the TI which has modes that allow you to enter ≫ x^2 - 1 = 0 and solve for x, Matlab cannot understand how to work with variables that are not set to a numeric value. In other words, it understands x = 4 + 7, because x is set to a specific number. It will then understand y = x + 5, and set y to 16. But it will not know what to do with 2*y = 3*x. If you want to solve for y in this expression, you must do it yourself using algebra, and then enter ≫ y = 3*x/2.

2. It does not understand implicit multiplication. 4(3+1) will generate an error message, rather than evaluate to 16.

Page 14: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 8

Class Problems

For every class problem, put two things into a Word document: the command that you entered into Matlab, and the result Matlab returned. Do not re-type anything; just cut-and-paste.

1. Using Matlab, calculate 2^100, and write it in the usual scientific exponential notation (for instance, 2.4∙1047 )

2. Using Matlab, calculate 2(6/13) +2.17−3.29

2

Tech Tip: Charge and Current

Two important quantities in ECE are current and charge. An accurate way of thinking of these quantities is by using the analogy of water being pumped through pipes around a closed circuit. Charge The amount of water, measured in gallons, is like electrical charge, measured in Coulombs, and abbreviated 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, and abbreviated A. Engineers typically use the variable “I” to stand for current, such as I2 = 12 A. The relationship between charge and constant current You can intuitively understand the relationship between a steady current flow and amount of charge that passes: if 2 gallons per second of current passed a point, in 3 seconds there would be 2 g/s * 3 s = 6 gallons of water that flowed. In the same way, if there was a constant I = 2 A of current that flowed in a wire for 2 seconds there would a total charge that passed of Q = 2 A * 3 s = 6 C. For constant current flow I Amps over a period of t seconds, the general equation for total current Q in Coulombs is

Q = I t (1) Graphically, this is shown to the right. Important: Notice that instead of the formula (1) above, the charge that flows from time 0 to time t1 is also equal to the area under the current line between t = 0 and t = t1. This is true even if the current changes with time. Think about this using the water analogy until it seems obvious.

PUMP

time

current I(t)

t1

Charge = current x time

= area under I(t)

Page 15: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 9

Class Problems

3. 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 units!)

4. A car’s headlights were left on overnight for 8 hours. If the headlights draw 0.75A, use Matlab to calculate how much charge they drew overnight.

Pro tip: Use a weekly or monthly planner

During the first few weeks of college many students feel overwhelmed by the number of things vying for their time. Schedules, syllabi, and a constant flow of emails with upcoming tests, projects, quizzes, parades, athletic meets, appointments, and training can get overwhelming. The solution is to purchase a small weekly or monthly calendar that you can carry and put all your dates into it – then you can safely delete the emails and not worry about missing anything. My favorite is to put them on a cloud-based scheduler like Outlook – which is VMIs preferred program – and then print a copy so you can carry it around with you in your hat, ready to quickly add dates as they come up. Every few weeks update your electronic calendar with your handwritten dates, and print out a new copy. If you lose your hardcopy, you’ve only lost the newly-added handwritten data. If you’d prefer something more aesthetically pleasing than Outlook, http://www.calendarpedia.com/ has many good-looking templates in Word and Excel format. Other tips: I don’t recommend daily calendars – they are designed for people who schedule hourly appointments, and aren’t suited to providing the big weekly or monthly picture at once. To make best use of these as planning tools, review your calendar every week and set a very few (2-4) major weekly goals (e.g. draft history essay, study for HI104 exam, ask parents to send a birthday gift for dyke).

Digging Deeper: For those of you who have taken calculus, you will recognize the above formula

for constant current Q = I x t generalizes to 𝑄 = ∫ 𝑖(t)𝑑𝑡𝑡1

0 for changing current i(t). Yet, the

concept remains that the current is equal to the area under the current graph.

Page 16: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 10

Week 2

Variables

Matlab can make it easier to perform complex calculations by using variables. For example, if a design equation says resistor R1 can be found from the equation:

R1 = 1

2πfC− R2

and we know f = 2000, C = 20∙10-9, and R2 = 3000, while you could type ≫ R1 = 1/(2*3.14159*2000*20e-9) - 3000

it is less error-prone to type ≫ f = 2000;

≫ C = 20e-9;

≫ R2 = 3000;

≫ R1 = 1/(2*pi*f*C)-R2

Notice several things in this last example:

1. Why we’re using variables: it makes the problem statement more natural. It also makes it easy to re-run the problem for a different value of R2, for instance; just change the R2 line and then re-enter the R1 = 1/(2*pi*f*C)-R2.

2. Pi: One can’t enter Greek characters directly, but there is a built-in constant called “pi” that is defined to be π.

3. Semicolons at the end stop Matlab from echoing the result of that line. E.g.

≫ f = 2000

will cause Matlab to parrot the result right back,

f = 2000

This is unnecessary when declaring variables, so suppress echoing with a semicolon:

≫ f = 2000;

Naming and inspecting variables

Variable names must begin with a letter. They may be any length, and capitalization matters. Electrical engineers tend to name resistors as R, R1, R2, R3, etc., capacitors as C, C1, C2, frequency as f, time as t. Do not forget: R1 and r1 are different variables. Variables may be composed of letters (lower and uppercase), numbers (but not as the leading character), and the underscore _ character. Some valid variable names: R27 f

index

Whats_the_frequency_Kenneth

Page 17: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 11

Invalid variable names: 3R

$spent

done?

Once a variable is created, it stays defined until you shut down Matlab or explicitly 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 in

≫ clear('R27')

Every time Matlab is run, it starts “clean” with no user-defined variables from previous sessions. It is common to need to see what variables are currently defined, and to do that, 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 (that would better be called the “Variables” window), f and R1 now appear with their current value.

Variables in Matlab defined in the middle command window are reflected in the workspace (‘variables’) windows on the right.

Class Problems Which variables are valid? If they are not valid, explain why. 5. TheAnswerIs42 6. SePtEmBeR21 7. 2B_or_Not2B 8. R1 9. Current&7

Page 18: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 12

Parentheses and implied multiplication

Unlike most calculators, Matlab does not understand implied multiplication, such as ≫ 4(3+7)

or ≫ a=7;

≫ 3 a

Instead, multiplication must be explicitly written out with a * ≫ 4*(3+7)

or ≫ a=7;

≫ 3*a

Tech Tip: Voltage, Current, Charge, and Resistance

We already presented an analogy between water flowing in a closed loop set of pipes and electric current flowing through a closed set of wires: the amount of water in gallons flowing past a point in a time interval was like the charge that flowed in Coulombs past a point in a wire in a time interval. The amount of water flow, measured in gallons per minute, was like the amount of charge flow, called current, and measured in Coulombs per second or more conveniently, Amps. To complete the analogy, the pump that creates a pressure difference in the water to make the current flow is like a voltage source, the pressure difference between any two points is like a voltage difference, and the resistance in the piping system to the flow of water is like a resistor. In summary, these are shown below with their schematic symbols.

Quantity Abbrev. Units Water analogy

Charge Q Coulombs (C) Volume of water in gallons

Current I Amps (A) Flow of water in gallons per second

Voltage V Volts (V) Pressure difference

Resistance R Ohms (Ω) Narrow pipe causing resistance to water flow

To create a circuit – the electrical analogy of a closed pipe system with a pump and narrowed pipes offering resistance to water flow – we need the following components:

Component Schematic symbol Water analogy

Wire (straight line) pipe

Voltage source

pump creating a pressure difference

Resistor narrowed pipe resisting water flow

An example of a simple electrical circuit and its water analogy is shown below. Take a moment to absorb the intuition here – be able to “see” the electrical current flow through the circuit, as it is pressurized to flow by the voltage source, and loses that pressure as it squeezes through the resistor.

Page 19: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 13

PUMP pressure

current flow

V (voltage)

I (current)

A pumped water system on the left and its analogous electrical circuit on the right. The pump creates a pressure difference to encourage water to flow through a restricted pipe, as the voltage source (for example, a battery) creates a voltage difference that causes electrical current to flow through a resistor. The resistance in the pipe and circuit are necessary to keep infinite current from flowing.

Class Problem

10. Using the above analogy, would current increase or decrease as the resistance (of the pipe or the resistor) increases?

Tech Tip: Ohm’s Law

About two centuries ago, Georg Ohm summarized the relationship among current, voltage, and resistance with the formula named after him. It is:

V = I R (1)

where V is voltage, I is current, and R is resistance. Be able to “see” this in terms of the water analogy; it is saying two different ideas:

1) voltage is proportional to current; as more water current is forced through a narrowed pipe, a greater pressure will develop across it, and

2) voltage is proportional to resistance; as the pipe narrows and its resistance increases, water flowing through it will also cause a greater pressure to develop across it.

There are two other formulations of Ohm’s Law, one solved for current and one solved for resistance:

I =V

R

similarly,

R =V

I

Page 20: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 14

Class Problems

11. A 68Ω resistor has 2.4A of current pumped through it. Use Matlab to compute the amount of voltage that must be across the resistor.

12. That same 68Ω resistor is now connected to a 120V voltage source. Use Matlab to compute the amount of current that flows.

Special symbols: i, j, and π

Electrical engineers use imaginary numbers very frequently, for instance 3 + j7, where j = √−1 . This is different than the way most mathematicians would write it: 3 + 7i. Engineers use j since i is reserved to mean current, and we place the symbol in front of the number rather than behind

it. Matlab uses both the i and j keys to mean √−1 , so 3 + j7 would be entered in Matlab as

≫ 3+j*7

Another constant that electrical engineers use surprisingly often is the ratio of a circle’s perimeter to its diameter, or π. In Matlab it is called:

≫ pi

Although only the first few digits are displayed on the screen, internally Matlab keeps track of it to about 16 digits.

Formatting numbers

Internally Matlab keeps track of all numbers to about 16 digits of precision, but by default only displays numbers to 4 decimal places. You can always see more digits in any answer by typing

≫ format long

Typing

≫ format short

returns Matlab to displaying the default form rounded to four decimal places. In your electrical engineering classes we normally keep Matlab in short format and typically only report 3 significant digits in our answers. This is because the components we use – resistors, capacitors, and inductors – rarely have more than 3 significant digits of accuracy in their values, and the instruments we use to measure voltage and current in undergraduate laboratories typically are limited to about 3 significant digits as well.

Digging Deeper: Curious 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 about 15.6536 digits.

Page 21: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 15

Scientific notation

Very large and small numbers are more easily read in scientific notation. For example, a typical capacitor used in our field available in the standard parts box is a 6.8*10-12 Farad capacitor. It would be much harder to pick one out from the parts cabinet if the labels were 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 multiplication (which Matlab does not do) but a shortcut that gives the same result as entering 6.8*10^(-12) but is easier to enter and read (and internally to Matlab, faster to process). Similarly, Matlab would return the answer of this value as:

≫ 6.8000e-12

since it by default returns 4 decimal digits in its scientific notation format. Later in the course we will introduce engineering notation which is an even more compact way to write these values than in scientific notation.

Exponentials and their inverses (exp, ^, sqrt, log, log10)

Electrical engineers frequently use the natural exponential function, ex. It is so common that rather than having a defined number for e and entering things as powers, Matlab has its own built-in function called exp(x). To compute e-1 for example in Matlab, rather than typing 2.718^(-1) one would type

≫ exp(-1)

The inverse of the natural exponent is the natural logarithm. Some mathematical textbooks call this ln, as in ln(2), but Matlab calls it log, as in log(2). So

≫ log(exp(-3.5))

equals -3.5. Electrical engineers often use base-10 logarithms when analyzing signals whose amplitudes vary widely. The loudness of a signal, for example, is commonly measured in decibels, which involve base-10 logarithms. To find a logarithm to the base 10, e.g. log10(10000) = 4, use the Matlab command log10(), as in:

≫ log10(10000)

Raising numbers other than e to various powers, as discussed above, is done using the ^ symbol, for example 232 is accomplished in Matlab with

≫ 2^32

Page 22: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 16

The square root of a number can be found in Matlab with the sqrt() function. For example,

√65536 (another common number in our profession) is found by typing

≫ sqrt(65536)

Class Problems

13. Use Matlab to evaluate 𝑒−5

14. Use Matlab to find 20 log10(1

√2) This number, surprisingly close to an integer, turns up

frequently in filter design problems.

Trig functions and their inverses

Electrical engineers frequently use trigonometric functions, especially cosines, to represent signals. Matlab’s trig functions are cos(), sin(), and tan() to find the cosine, sine, and tangent of a number given in radians. For example, cosine(π/2) is found by typing

≫ cos(pi/2)

Inverse trig functions are given by acos(), asin(), and atan(), where the result is returned in radians. For example, the inverse cosine in radians of -0.5 is

≫ acos(-0.5)

Since engineers often use degrees, an alternate form of these commands are available that take their argument in degrees: cosd(), sind(), tand() and their inverses that return their answer in degrees: acosd(), asind(),atand(). For example, to find the inverse cosine of 45°, use this Matlab command

≫ acosd(45)

Matlab returns 0.7071.

Math review: there are 360° 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.

Math review: Need to find a root other than a square root? Cube roots and higher are the same as taking reciprocal exponentials. For

example, √10247

= 1024(

1

7). Matlab’s ^

function will thus let you find any root.

Page 23: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 17

Tech Tip: Using a DMM to measure a steady voltage

Modes: Modern digital multimeters (DMM) at first sight are imposing, but you will soon be using them like a pro. To measure a voltage you must first set up the DMM. Most will have five basic settings to measure (see the figure below), so move the selector switch to DC voltage. Possible modes are typically:

AC (varying) voltage, marked with

DC (constant) voltage, marked with

AC current

DC current

Resistance

Range: Multimeters may autorange like the one on the right, or may require manual adjustment. If autoranging, it will move the decimal point in the measurement to make the reading as precise as possible. Manual ranging DMMs split each type of measurement (voltage, current, etc.) into different ranges, for instance a 2V-20V range and a 20V-200V range. For a manual ranging meter, select the lowest voltage greater than the one you expect to measure. For instance, if measuring a 1.5V battery and the DMM offers ranges of 0.2V, 2V, 20V, and 200V, choose the 2V range. Probe jacks: Next, plug the probes into the correct jacks. There are always two sets of probes, one red and one black. There are usually 3 or more different jacks to place them. The black probe always goes into the jack labeled “COM” or “COMMON”. The red probe will go into the jack labeled “V” or “Volts”. Probe tips: The red probe goes to the more positive end and the black tip to the more negative end. In the photo above, the battery, nominally marked 1.5V, is actually reading 1.78V. If the probe tips were reversed, the DMM would read -1.78V.

Creating vectors

So far Matlab variables have been scalars; 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 discussed so far. Using the y vector defined above,

≫ cos(y)+1

yields

ans =

1.8439 0.0100 1.5253 0.0959 0

Page 24: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 18

Regularly-spaced vectors can quickly be created using a colon using the format start : increment : end. It is easiest to understand by example.

≫ x = 0 : 0.25 : 3.5

is equivalent to

≫ x = [0 0.25 0.5 0.75 1 1.25 1.5 1.75 2 2.25 2.5 2.75 3 3.25 3.5]

Random vectors can also be quickly created using the rand() function. A vector with N numbers in it can be created using rand(1,N), for instance

≫ x = rand(1,10)

returns this time (of course, for you it will be different or they won’t be very random numbers!)

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.

Use of the semicolon

The semicolon ; is commonly used in Matlab for two different purposes: 1) It permits multiple statements to be on the same line. For instance, instead of typing

≫ R1 = 2

≫ R2 = 5

≫ Rparallel = (R1*R2)/(R1+R2)

one could save space and type

≫ R1 = 2; R2 = 5; Rparallel = (R1*R2)/(R1+R2)

2) It suppresses output. Normally if you type

≫ R1 = 2

The command window echoes back on two separate lines

≫ R1 =

2

This is unnecessary for a simple assignment and can be suppressed by ending the statement with a semicolon like

≫ R1 = 2;

Suppressing output is very important when generating large vectors to prevent your screen from filling with data, like

≫ mydata = rand(1,2000);

Page 25: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 19

Plotting data

Matlab has an extremely comprehensive set of plotting abilities, many of which we will explore in Module 3. As a brief preview, try creating a rough sinewave using

≫ x = 0 : 0.1 : 4*pi;

≫ y = cos(x);

≫ plot(x,y)

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.

Class Problem

15. Plot a triangle with vertices at x = [0 1 .5] and y = [0 0 .7]. Hint: You may think you need just three points to define your triangle, but you’ll need a fourth to close it, where the final point is a copy of the starting point. To cut and paste the figure into Word, under the Edit menu in the plot choose “Copy Figure”.

Getting help

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 attempt to teach how to use the system as a whole. A study guide attempts to guide a learner by introducing commands in many small chunks that build upon each other. Matlab has two different built-in reference manuals, one very abbreviated called help, and the other detailed called man. To get quick but abbreviated help with the syntax of a Matlab command type:

≫ help <command>

for instance

≫ help plot

This returns the following 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

Page 26: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 20

plot(X,Y,S) where S is a character string made from one element

from any or all the following 3 columns:

b blue . point - solid

g green o circle : dotted

r red x x-mark -. dashdot

c cyan + plus -- dashed

m magenta * star (none) no line

You can get comprehensive help by typing

≫ doc <command>

for instance

≫ doc plot

from within Matlab will spawn a reader covering the desired command in great detail over many pages.

Saving and loading variables

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; a vector may be defined to hold all the close-of-day trade stock prices for IBM, for instance; that data would have over 20,000 numbers in it. To save a variable x, which may be real or complex, scalar or vector, in file called “x.txt” in ASCII format (that is, a format that you can read and edit in a program like Notepad), enter

≫ save('x.txt', 'x', '-ascii')

Note that the filename comes first, encased in single quotes, then your variable in single quotes,

and then the '-ascii' option to save the data in an easily-read and modified format, with each part separated by a comma. Omitting the '-ascii' option will save the data as a compressed .mat file that takes less disk space but is essentially unreadable by any program other than Matlab. That is a difficult-to-remember syntax. Don’t try to remember it; just know the name of the

save() command and when you need to use it get help with

≫ help save

If you close and restart Matlab, clearing the variable x from memory, you can reload it by typing

≫ load('x.txt')

This is also a simple way to import data generated by external sources into Matlab. More complex data can be imported by right-clicking the data file in the folder window and choosing “Import Data”.

Page 27: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 21

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 keyboard shortcuts very convenient. To recall previous commands, press the up arrow key ↑. Keep pressing to go further back in the command history. Once the command is visible in the command window, you can change it or run it again by pressing “Enter”. Another way to re-run a command is to look in the command history window, circled to the right. While this is easier to remember than using the up arrow key, the arrow key is much faster.

Pro tip: Goal setting

As a college freshman and electrical engineering student, it is vitally important to set goals because it you do not, other people and things will.

If a member of the RDC feels your performance is lacking, you will hear about it, immediately, and in no uncertain terms. If your academic performance is lacking, will your professor know about it as quickly, or be as vocal as your friends in the RDC? Yet, are cadets more likely to get in serious trouble, the type of trouble that keeps them from graduating, by the RDC or academics?

The lesson is clear. Do not let your goals be set by the person yelling the loudest. Or by your roommate who needs to vent his ratline stories. Or the video game you just installed. Or by anyone or anything else but you.

Both scientific research3 and some of the world’s top executives4 both give the same advice that work as well for college students as CEOs: At the start of each week, review your calendar and make a list of 2-4 goals for the coming week. Each night, review your calendar and make a list of 2-4 goals smaller for the next day. As a VMI cadet you can carry them on a 3x5 card in your hat. It will help you keep them in mind and make them happen, all by making your silent inner voice louder than the person yelling in your ear.

3 For example: Locke and Lantham, A Theory of Goal Setting and Performance and Task Performance, Prentice Hall, 1990. 4 Many Fortune 500 CEOs do this, including Steve Jobs of Apple and Kenneth Chenault of American Express. Perhaps the most famous: Benjamin Franklin.

Page 28: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 22

Matlab commands used in Module 1

Basic math operations + - * / ^ * means multiply. No implied multiplication. sqrt() square root log() natural log log10() log base 10 exp() natural exponent Predefined constants and notation i, j sqrt(-1), can be used for instance as 3 + j*7; pi π Formatting numbers 68e-12 type of scientific notation, here representing 68 x 10-12 format long shows all significant digits (about 16) format short shows about 4 significant digits of answer Saving and loading data save(‘x.txt’, ‘x’, ‘-ascii’) saves variable x in an ascii-readable file x.txt save(‘x.mat’,’x’) saves variable x in a compressed Matlab format x.mat load(‘x.txt’) loads the variable in x.txt back into variable x Trigonometric functions cos(), sin(), tan() cosine, sine, and tangent functions given an argument 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 Vector functions [2 4 -6] creates a vector with components 2, 4, and -6 12:3:24 shorthand for [12 15 18 21 24]. The middle increment number may be negative; 10:-1:0 counts down from 10 to 0. rand(1,17) a vector of 17 random numbers, each independently ranging from [0 1) Plots plot(x,y) plots the set of positions 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.

Page 29: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 23

Lab Problems

These problems require more thought than the Class Problems that were designed to check general comprehension. To answer create a Word document and for each question turn in the command typed into Matlab and the result. No Matlab command = no credit. E.g. 1. Matlab: 4+(5^(1/6)) Answer: 5.3077 1. Using Matlab, calculate 28. This is an important number in ECE since many single-chip

miniature computers, called microprocessors, move binary data around in sets of 8 bits, called a byte. These 8 bits, each of which may be 0 or 1, provide 28 = 256 unique states, so a byte can represent any integer from 0 to 28-1, or 0 to 255.

2. √3 + √43

(Hint: read the Math Review shaded box)

3. Use Matlab to determine what famous irrational number, used frequently in signal processing, that this continued fraction is trying to approximate:

3 +1

7 +1

16

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

5. A car’s headlights were left on overnight for 8 hours. If the headlights draw 0.75 A, use Matlab to calculate how much charge they drew overnight. (Units matter here; an hour and a second are not the same!)

6. If you cut a wire and separated the ends in the above right schematic, all current stops flowing. What is the equivalent of cutting the wire when done to the pipe analogy? (Hint: it isn’t just cutting the pipe because then water would flow everywhere).

7. A 120V voltage source is connected across a resistor and 6.8 Amps of current flows. Use Matlab to compute the value of the resistor.

8. A 12Ω resistor is connected to a 14V source. Use Matlab to compute how much charge flows through the resistor after 2 seconds. Hint: you will need two formulae.

9. Engineers use some unusual numbers; e and π are both irrational numbers (about 2.71

and 3.14 respectively), and the imaginary number j = √−1 is so unusual that even its discoverer, Euler, said it was merely a mathematical curiosity of no use. But they combine in a surprising way that later EE courses will put to good use. Use Matlab to evaluate the following and write down the first 10 significant digits (hint: if you’re not surprised, you did it wrong): 𝑒𝑗2𝜋

10. Use Matlab to find the cosine of π/6 radians.

11. Use Matlab to evaluate the cosine of 60°

12. Create a plot with the x axis extending from 1 to 50 of 50 random numbers. Hint: you need an x vector that counts from 1 to 50, and a y vector that has the random numbers. Show the commands you used to make them (do NOT waste paper showing the contents of the vectors) and include the plot.

13. Plot the first letter of your last name. It may be very rough; if your last name begins with “S” for example, a jagged reversed “Z” shape is fine, for instance, as long as it is recognizable.

Page 30: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 24

Page 31: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 25

Module 2: Matlab as a calculator

Objectives

When you complete this module you will be able to use Matlab as an advanced calculator to:

Build and manipulate vectors

Perform vector mathematics

Work with complex numbers (Signals and Systems)

Change rectangular to polar complex number formats (Circuits Analysis)

Build and manipulate matrices

Solve large simultaneous equations (Circuit Analysis)

Vectors

(Definition)

Creating Vectors

Explicitly define the components: [2 3 1] Vectors filled with the same value:

zeros(1,5) ones(1,12) Note: can multiply scalar with a vector; combined with ones() this lets you fill a vector with

any number. 4*ones(1,6) -pi*ones(1,10)

Note: can multiply scalar with a vector

Page 32: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 26

Vectors filled with evenly-spaced values: know the increment

[start:increment:end], e.g. 0:0.5:20 same as [0 0.5 1 1.5 2 … 19 19.5 20]

Vectors filled with evenly-spaced values: know the total number of values

linspace(start, end, number of values), e.g. linspace(0,3,7) same as [0 0.5 1 1.5 2 2.5 3]

Vectors filled with random numbers

rand(1,10) fills with 10 random real numbers, each of which is between 0 and 1 10*rand(1,20)-5 creates a vector with 20 random numbers, each between -5 and 5 Class problem: what does…do Lab problem: make it go b/n * and *

Tech tip: Types of R’s Demo: DMM, R’s Tech Tip: Using a DMM to measure resistance Pro tip: buying a DMM: get one with sound continuity for debugging, diode/cap checking

as well as AC/DC voltage, DC current, and resistance. Some also can read frequency. semicolon, disp, length accessing/changing value v(4) removing elements – what does that mean – setting to zero or []=0 adding elements a=[b c], or a=[1 a], or a = [a 1] complex numbers

How much copiable from EE431? I vs. j Real/imag vs. mag/phase Complex exponentials e^i3pi, plot(real())

Lab problem: H(w) = (j w R C)/(j w R C + 1) for several values of w, and display in native and polar form. Don’t explain what that is; just say it is something to plot.

Page 33: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 27

Common functions that take vectors: most standard (e.g. + * sqrt, sin) , mean, std, root, poly, length, real, imag, plot

transpose vector math vs. element-by-element math using dots. Important for *, /, ^ strings (making with ‘ ‘, substrings) converting between numbers and strings

Tech Tip: R’s in series and parallel Class question: create vector of 10 basic 5% values from 1 to 8.2 Lab question: use multioplication and Class q: Matlab to compute two R’s in parallel Demo: R card Lab q: Make a vector of all the R values. Hint: if you call your answer to CLass Quesiton 2 vR,

what is 10*vR? What is [vR 10*vR]? ------------------------ Module 2B Matrices – definition

creating: zeros, ones, from vectors, rand() semicolon, size (not length) strings accessing/changing a value m(4,2), or a row m(:,3), or column m(2,:) removing elements – what does that mean – setting to zero or m(4,:)=[] transpose matrix math vs. element-by-element math using dots functions that take matricies: most standard math,

Protip: college, calculator is king since exams. But in industry/grad school, it is Matlab. I realized I hadn’t used my calc in months! Tips in buying a calc good for VMI: must be able to handle complex matricies. TI 86 and below won’t. Don’t be mislead into purchasing an expensive instrument with many specialized engineering functions.

Solving simultatnous equations using matricies Demo: flying levitator

Tech Tip: voltage divider: The formula relating V1 to Vin, R1, and R2 is: 𝑉1 = 𝑉𝑖𝑛𝑅1

𝑅1+𝑅2.

Tech Tip: mesh and nodal analysis methods lab question: mesh example lab question: voltage divider with vectors lab question: mesh equation example: 122 book page 21 lab question: complex filter

Page 34: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 28

Module 3: Matlab graphics

objectives; plot, xlable, ylabel, title, grid, xlim, ylim, subplot, hold, semilogx start with figure of types of EE-useful plots we’ll cover: line (v vs. t), scatter (phase vs.

amplitude), bar (EE120 grades) line plot – most important!

axis labels and titles line color. ‘linewidth’, ‘linecolor’, ‘linestyle’ multiple lines using hold on, hold off grid axis limits axis([0 10 -2 -5]) logarithmic axis scaling

scatter plots Tech Tip: Oscilloscopes (and scope style: v vs. t, grid) Example: plot this waveform in scope-style from 0 to 5 seconds. Label everything. Cos(3t)-2. Demo: Oscilloscope. R=160, C=1uF, fcrit = 1kHz), try driving with a 500Hz showing double

trace and 5kHz with double trace. Before class begins, leave on with ( .1uH + 100 ohm + 2uF in series, driven by a 50Hz squarewave for decaying sinusoid τ = 2ms, f = 13kHz).

Lab: plot this waveform in scope-style from 0 to 10 seconds. Label everything. 2+exp(-t/5)*cos(2*t).

Class: given vector of voltages over a powerline plot them with labels Class: given vector of 11 voltages over 1 second, plot them with labels Class: given matrix with top row of voltages, bottom row of currents, plot both, with labels. Pro tip: finding the right study area for you ------------------

module 3b: Matlab graphics barplots multiple separate plots, each with its own axis advanced plot decoration using the plot editor

line thickenss axis on/off changing text font and style

greek symbols in text Tech tip: Ω ω α β λ ζ π δ μ Δ Σ Π τ

exporting to Word Pro tip: Ethics: What’s the difference b/n cheating on a math test and lying about your age to

get a cheaper movie ticket? Your roommate creates an offensive Meme personally attacking the RDC. The RDC chair wants to know who did it. You are the only one who knows. Do you tell? Would it make a difference if the Meme attacked a member of the Commandant’s staff known for boning cadets and it was the cadet’s dyke who wanted to know?

other Matlab plotting (short bit on errorbar, 3D solid, 3D mesh) Tech tip: What are low pass filters?

Page 35: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 29

Example: plot 2 signals, top and bottom, each with two lines before and after with same lowpass.

Class questions: damped oscillations plotting with alpha damping Class questions: Using Matlab, (do some basic complex questions like on EE431) Class questions: re-create the barplot of grades given in the front cover Tech Tip: Bode plot standard (amplitude vs. frequency, log x, dB y) Demo: Digital VST with adjustable LP filter on Amen break. (or something cool VST‼) Tech Tip: what are lowpass filters. Redo class q from 3a but this time plot using Bode plot

styling over range of freqs Class question: plot the following Bode-style filter response of |H(ω)| = … Tech Tip: resistor standard values Lab question: some simple complex numbers lab questions: plot complex roots of filter in s-plane lab questions: more complicated filter like H = 1/(2pi RC + 100). Plot magnitude as w varies 1

to 1000. Lab question: above, but logscale the x axis (remember not to use linspace for w but logspace) lab question: create scatter plot of R’s using standard values from ** to **. Then again, using

log of R’s. lab question: There is the following set of grade data. Create a bar plot with it using the same

bins as on the cover of the module.

Page 36: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 30

Module 4: Introduction to Matlab Programming

Lecture notes: for these, class and lab problems put into a word document with the code and the input/output of the check program.

Why program? Hide complexity from user, frequent need to do the same calculation Scripts: a simple approach to programming

Example: Parallel resistance (hardcoded R’s). Show how to use the editor. (change to your m: drive, start programming window, type program in asci, save as scriptName.m

Class problem: ISolver (given V, R, calculate I) Pro tip: Feeling overwhelmed? List 3 thigns. Next action. Demo: Fire electromagnetic gun Functions

Problems with Scripts: consider wanting to use parallel as part of another program. You’d have to avoid using R1 and R2 in your program! Like saying the sin function always uses

Functions vs. Scripts. No variable conflicts. Functions pass variables in and out, leave no variables.

Built-in functions Example: Creating generic function – say time in, voltage out. Show how to use the editor.

(change to your m: drive, start programming window, type program in asci, first line: function output – functionName(input 1, input 2, etc.), save as functionName.m.

Example: Parallel resistance. Class problem: [mag, phase] = Complex2Polar(z) Tech tip: Consider creating your plots using custom functions Example: First order lowpass filters (note: definition of LPF discussed in 3b). Develop code

to plot filter response over range of f Class note: modify above function to plot the absolute value of the filter’s response vs. f Lab problem: NeedGrade(g1, g2, gd) Lab problem: NeedGrade2(g, d) takes vector of any grades in g, single desired grade in d.

Hint: sum, length Lab problem: out = Factorial(in). in integer >= 0. Hint 1: use either prod or sum here.

Hint: given integer n, what does [0:n] do? Lab problem: You have 2 resistances. You can use them individually or in combination to

get 4 different values of resistance. Write a program that given 2 resistors, R1 and R2, outputs a vector with every possible value of resistance (that is, R1, R2, their value in series, their value in parallel). Hint: use the parallel program in the earlier example.

Lab problem: much harder: do the same as above, but using 3 resistors. There’s 17 different ways to combine them!

module 4b: Matlab Programming #1: Scripts, functions

if, then, else statement Example: v(t) = -t, t<0, e^2t, t>2

Pro tip: Handling email (and how to get an appointment) Class problem: modify to 10t-5 for 0<t<10, 25-t for t>10. Plot for 0<=t<=25.

Page 37: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 31

Strings: create a=’I am a string’. Get a part of it a(2:4). Compare: strcmp. Convert to number: str2num(‘123’)

Tech Tip: Engineering Notation: pnum1kM Example: prefix to scaler

Class probem: modify above to work for all subscripts. Tech Tip: wire sizes Class problem: given a maximum current, compute the required wire size from a list of

standard ones. Demo Mini-Tesla (and wire size problem) Example, class problem: resistor color code decoder Lab problem: modify to make engform(‘124u’) and return 0.000124. Lab problem: given 2 resistors and a desired resistance, find the combination that gets you

closest. Lab problem: given Nicola Tesla, Charles Steinmetz, Michael Faraday, Rowan Atkinson, (two

more)

Page 38: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 32

Module 5: Programming 2: Looping

For-next: Concept – repeat an action a known number of times. E.g. do a calculation on a resistor 100 times.

Example: plot the v(t) function 2t-5, 0<t<10, 25-t, 10<t<20 for 0<t<20 Nested loops – example, go thorugh all possible R value pairs Class problem: Pythagorean triples, first 100 Class: create a vector of all possible parallel resistor pairs Tech Tip: Monte Carlo analysis Demo: tick rover (tick rover) Example of Monte Carlo analysis Pro tip: Post-Graduation Careers Lab problem: monte carlo: test filter cutoff for 100 values of toleranced resistor and run

through a Monte Carlo test. Bar graph result. Lab problem: go through all standard value R’s and find one or two (in parallel or series)

closest to given value

module 5b: Program #2: break Lab problem: given a desired resitance, find the standard value that is the closest. Lab problem: above, but you may also put two in series or parallel Example: ask user for voltage, return current, until user inputs a blank Tech tip: Phasors (complex number to sinusoid) Demo: ion gun input Lab: Keep asking user for a complex number and frequency, display phasor. If given a blank

input, stop Pro tip: IEEE, EIT, PE Tech Tip: Binary math (and Matlab) Lab questions: create a set of functions called addb, subb, mulb, divb. What to do with

remainders? Lab questions: Filter design Lab question: putting it all together: search for oil

Page 39: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 33

Module 6: PSpice

PSpice concept: Screen layout, new schematic, key buttons Pro tip: Ethics Common components - voltage sources & how to change them, Rs, C’s, Wires, Ground Types of analyses:

Operating point – DC input, what are the voltages/currents? (numbers). Transient – Changing input, what are the voltages? (waveforms vs. time). AC Analysis – Sinusoid of varying frequency in, what is the amplitude of the sinusoid out?

( Tech tip: what is ground? Demo: Tick Rover (ground shared b/n digital and analog parts) Voltage divider example Tech Tip: power and energy (work). Computing energy used by resistor in a network Tech Tip: battery capacity Pro tip: Disillusioned? lab question: question about battery and blanket.

module 6b: PSpice transient

Tech Tip: 555 (lecture note: why analog vs. digital? digital noise, EMF hard (lightning, space, nuke – demo

Tesla) demo: Big honking Tesla, motivated by above do the PSpice analysis of a blinker Pro tip: Stress busters

Page 40: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 34

Module 7: Putting It in Practice

build the blinker Big capactor discharge Tech Tip: capacitors and how they work Lab questions

Page 41: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 35

Case studies for ethics Coworker using bootlegged software. Buggy? No longer in business. + will lose contract. + is spouse. Case Study Michael McFarland [1] of Boston College recently published an interesting ethical quandary in IEEE Computer. The past several months, George, an electrical engineer working for an aerospace contractor, has been the quality control manager on a project to develop a computerized control system for a new military aircraft. Early simulations of the software for the control system showed that, under certain conditions, instabilities would arise that would cause the plane to crash. The software was subsequently patched to eliminate the specific problems uncovered by the tests. After the repairs were made, the system passed all of the required simulation tests. George is convinced, however, that those problems were symptomatic of a fundamental design flaw that could only be eliminated by an extensive redesign of the system. Yet, when he brought his concern to his superiors, they assured him that the problems had been resolved, as shown by the tests. Anyway, to reevaluate and possibly redesign the system would introduce delays that would cause the company to miss the delivery date specified in the contract, and that would be very costly. Now, there's a great deal of pressure on George to sign off on the system and allow it to be flight tested. It has even been hinted that, if he persists in delaying release of the system, the responsibility will be taken away from him and given to someone who is more compliant. What makes the situation so difficult for George is that he must choose between conflicting duties: loyalty to self, family, employer, and superiors versus the obligation to tell the truth and to protect others from harm. Clare Bartlett SDX Alliance is a large company that sells computers, computer components, and software. Ralph is hired as an entry-level software engineer at SDX Alliance. His first project was to assist in writing the code for SDX Alliance’s new hard disc controller. He had previously worked on a similar system interning at a start-up and had written a code which greatly enhanced the performance of their product. Ralph quietly re-uses this same code in the SDX Alliance product, and does not think to tell anyone that he has used the code from his last job. His manager is thrilled with the speed improvements this code brings to the product. Before the product is released, it has to undergo a four-month long quality assurance process review. During the review of the product, it was found the code which Ralph developed had been copyrighted by the startup he had previously worked for. Even though Ralph had developed the code, his previous company still owned the intellectual property rights to it. When his manager informed Ralph of the problem, Ralph admits he did not realize he had made a mistake because he was not familiar with copyright laws. Ralph then goes on to explain that the start-up he used to work for is now out of business and is unsure if SDX Alliance would be able to get in contact with the owner of the copyright. If SDX Alliance can’t use Ralph’s code, then it will have to rewrite the entire code of the product, delaying its release by many months. What should they do? Clare Bartlett was a 2014-2015 Hackworth Fellow in Engineering Ethics at the Markkula Center for Applied Ethics at Santa Clara University.

Page 42: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 36

Nabilah Deen Jack has been working as a project engineer for an electrical energy technology firm for a few years now, and has recently been promoted to review projects for in-need communities overseas. He has been put in charge of managing the current company’s charity projects, and determining how to distribute the funding for them. Some of the projects are pretty straightforward in their mission and material requirement, but for one project, Jack isn’t sure whether the company should be funding it. The project’s mission is to provide new solar panels for an East African community but the project data suggests it is more practical to just install better lighting inside the homes. Jack wonders whether to bring up his doubts with his boss. Based on the company’s research on the community, the community desires better lighting system for their homes, and the solar panels would be an expensive and high maintenance project. Not to mention, there was a previous project that (when followed through) resulted in equipment being stolen from the same region to exchange for money. Jack understands their local sponsor would gain a great advantage in featuring solar panels in the community. It would also foster a good business partnership between the two companies. However, Jack feels it is his responsibility to provide the community with a more simple and efficient solution to their problem, without diving into a large project that could possibly lead to negative side effects. Is Jack’s company wrong to provide technology to the community when they don’t need it? Nabilah Deen was a 2014-2015 Hackworth Fellow in Engineering Ethics at the Markkula Center for Applied Ethics at Santa Clara University. August 2015 Aug 26, 2015 As a graduate student your thesis involves work on signal processing routines that can identify a type of cardiac (heart) disease based on analysis of electrocardiogram (ECG) signals. ECG signals are the voltage signals measured on the chest surface that propagate from the electrical depolarization of the heart as it beats. Manufacturers X and Y go to court over a dispute of patent rights involving a system that uses a related technology, and you are offered as a graduate student a temporary 2 week job to work as an expert witness for company X. Your job is to explain to the judge why Y’s approach infringes X’s patent claims. As you prepare for the case, you write down the many reasons that this is true, however you also realize there are several reasons that the opposite argument may be made. At the trial, after you deliver your report, the opposing lawyer asks you during cross-examination if you have any reasons to doubt your reported findings. Does your ethical obligation to your client company X outweigh your ethical obligation to completely disclose your doubts? Would your answer change if the opposing expert witness testified first, and when faced with the same line of questioning answered “of course not,” giving the judge an obviously-biased view?

Page 43: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 37

Note: Know what matrix (including vector) multiplication means. [1 2] * [3 4] gives an error since matrix multiplication is only defined when the number of columns of the first matrix (here 2) equals the number of rows of the second (here 1). [1 2] * [3; 4] (where the semicolon means “start a new row”) is defined (since 2 = 2) and gives a matrix answer with the number of rows of the first number (1) and the number of columns of the second number (also 1)…it gives a single number answer of 1*3 + 2*4 = 11. If you want the answer [1*3 2*4] = [3 8] then prefix the * sign with a period, like this: [1 2] .* [3 4] = [3 8]. Yet another note: In Word you may occasionally want to use a mathematical or Greek

symbols like 2 ± 0.3 or 4 34 or δ[n]. You can find them all in the Symbol font. Choose Insert, Symbol, and change the font to Symbol.

Problem 1 Express each of the following complex numbers in rectangular form using Matlab: a) j ej 11 π / 4

b) (1-j)10

Problem 2 Express each of the following complex numbers in magnitude/angle form in radians using

Matlab: a) j ej 11 π / 4

b) 3 + j6

4. Creating and plotting vectors and matrices

Examples v = 1:10; % shorthand for saying v = [1 2 3 4 5 6 7 8 9 10];

v = 0:0.1:5; % creates the vector [0 0.1 0.2 0.3…4.8 4.9 5]

v = linspace(0,2,50); % creates a vector of 50 points, linearly spaced between

0 and 2

m = zeros(4,5); % creates a matrix of zeros that is 4 rows by 5 columns

v = ones(1,10); % creates a column vector of ones that is 10 long. plot(x,y); % plots x vs. y using lines to join the {x,y} point locations plot(x,y,'.'); % plots a single point at each {x,y} location title, xlabel, ylabel % labels the plot

To insert a plot figure into a Word document, from the figure's menu choose Edit Copy Figure; then cut and paste into Word. To plot the equation y = x/2 * cos(x) between 0 and 5 a) First create the x vector with enough points to give a smooth plot x = linspace(0,5,100);

b) Next, find y at each point location x y = x ./ 2 .* cos(x);

Page 44: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 38

Note 1: when working with vectors you must use .+, .-, .*, ./, and .^ for element-by-element add, subtract, multiply, divide, and raise to a power.

Note 2: cos(v), sin(v), tan(v), exp(v), log(v), and log10(v) work fine for scalar, vector, or matrix arguments.

c) Plot it using plot(x,y) Note 1: You can specify the color of the plot using plot (x,y,'r'), where r is red, b is

blue, k is black, and g is green Note 2: You can specify the line style of the plot using plot(x,y,'b-') for a solid blue

line, 'r--' for a dashed red line, or 'g:' for a dotted green line. plot(x,y, 'b.') plots a single blue dot at the location of each x,y pair and does not join x,y pairs by a line of dots, unlike the other line styles.

Problem 3: Plot y = real part of (e j x π ) as x varies between 0 and 5. Neatly label the plot.

5. Saving and loading variables

First, copy the data files for this lab to your working directory. a) Open a web browser and point it to my home page (www.jimsquire.com).

b) Navigate to the EE431 course page (Teaching EE431) c) Under the “Lab” section, right-click each data file and save it to the current working

Matlab directory. This time there is only a single file called Lab1.mat; just download this one.

You can see what variables are currently defined by typing

whos

You can also see the variables on the Workspace window that is usually to the left of the main Command window. Notice that not only the defined variables are listed, but also what size they are. Type it now.

You can load and save variables (for instance variables x and y) used by Matlab to a file (for instance, myfilename) using the command (note: no commas) save myfilename x y

Matlab will create a single file called myfilename.mat that will hold x and y. Note the .mat extension is automatically added, and that the syntax is the same regardless of whether x and y are scalars, vectors, or matrices. Also note that the file created is not an ASCII file readable by, say, Notepad; the variables are stored in a compressed form. You can also store variables in ASCII form, perhaps to be read by an external program; see help save for details.

The word "workspace" refers to all the variables currently defined by Matlab. After working for a while it is easy to get confused by the number of variables you have defined and you may desire to clear some of them. To clear variables x and y, for instance, type clear x y

Now type whos to see the effects. To quickly clear all of the variables in the workspace, type

clear

by itself. Do this now, and then type whos to see the effects. To load variables from a file, type

Page 45: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 39

load myfilename

The .mat extension is optional. Do this now to load the file Lab1.mat that you earlier copied from my homepage. You can also read in an ASCII text file; see help load for details.

Problem 4 Using the above commands, determine the variable names I have stored in Lab1.mat.

Page 46: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 40

6. Accessing vectors and matrices

To set scalar variable N to the length of vector v, type N = length(v);

You could see if the vector was a row vector or column vector by typing [nrow, ncol] = size(v)

For a row vector, ncol will be 1; for a column vector, nrow will be 1. The function length discussed above actually calls size and returns either nrow or ncol, whichever isn't 1.

Although one can multiply an entire vector v by 2 by saying v1 = v.*2; it is not always

desirable to access an entire vector or matrix at once. To multiply the third element of vector v by 2, you instead type

v(3) = v(3) * 2; % you don't need to type .* since both v(3) and 2 are scalars To add one to elements 4 through 8 of vector v1, type

v1([4:8]) = v1([4:8]) + 1;

To set elements 3, 5, and 9 of vector v2 to zero, type

v2([3 5 9]) = 0;

To remove elements 3, 5, and 9, type

v2([3 5 9]) = []; % this is probably the first time you've seen this trick! To multiply all the elements of v3 by 5 except the first two, type v3 = v3(3:end) * 5; % note that here "end" means "end of the vector" % also, you don't need .* since one variable is a scalar You can combine the above ideas with what you know about creating vectors v4(1:2:end) = []; % removes the 1, 3, 5, etc. entries in vector v4 Unlike vectors that just have a length, matrices have both a number of rows and columns.

Use size to determine this: [nrow, ncol] = size(m);

Accessing matrix elements is similar, but using row, column format m(4,5) = m(4,5) + 1; % adds 1 to row 4, column 5 of matrix m m([1:2], [end-1:end]) = 0; % sets the 4 elements of m that are in the first

two rows and last two columns to zero One trick with matrices is to use a colon to represent all the rows or all the columns

m(:,2) = []; % this deletes the second column (and all the rows) of matrix m m([1 3],: ) = 0 % sets the first and third rows of m (and all the columns) to zero. You can transpose a matrix (i.e. make 3x5 matrix a 5x3 matrix) using the transpose

operator '. m'

This also works to convert a row vector into a column vector or a column vector into a row vector

Page 47: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 41

v'

If you attempt to set part of a matrix or vector (e.g. m([1:2],[1:2]) for the upper-left 4

elements) to a different-sized matrix or vector (e.g. m([1:2],[1:2]) = [1 2 3 4 5] ) then you will generate an error message In an assignment A = B, the number of columns in B and number

of elements in B must be the same.

Page 48: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 42

Problem 5 Clear your workspace and reload the variables from the Lab1.mat file. Determine the command necessary to replace the third column of matrix m with the vector v5, and display the result.

You can also access vectors and matrices within a loop. For example, enter the following code at the Matlab prompt pressing the return key after each line: >> x = 3 * 0:0.2:5 + 2;

>> for i = 1:length(x)-1

y(i) = x(i+2);

end

>>

Note 1: Loops are usually used within m-files. When it is entered at the command line,

Matlab will wait to execute it until the end command is typed.

Note 2: This could be better done without a loop by typing y = x(2:end)

7. Writing scripts and m-files

a) Scripts Scripts are not programs, but just collections of commands that are run in a batch, just as if they

were executed at the command window, but saved as a file with a .m extension. Scripts are evil, but m-files (also known as functions) are good. Here is why: say you saved the following script as MyScript.m:

degF = input ('What is the temperature in degrees Fahrenheit?');

degC = 5/9*(degF-32);

disp(sprintf('The temperature is %g degrees Celsius', degC));

The commands disp and sprintf are new. Disp simply displays a value to the screen

without assigning it to default variable ans; type disp(4) and compare this to what happens

when you just type 4 (and press the return key). sprintf creates a string that has embedded variables replace each instance of %g.

Now, if you type MyScript at the Matlab command prompt, the script will prompt you to enter

a number, and will then display a different number on the screen. If you check your variables kept in memory after this by typing whos at the command prompt, you'll discover that both degF and degC are still taking up memory space. Worse, you can't call MyScript as you could a function such as y = sin(4) where the input argument 4 is passed to function sin, which then returns a number to y -- i.e. you can't say y = MyScript(70). Don't use scripts; m-files (i.e. functions) can do everything scripts can, and more.

b) M-file example 1

Best illustrated with an example, this is an m-file that extracts the last L elements from a vector x

function y = GetLast( x, L )

%GetLast returns the last L elements of vector x

% usage:

Page 49: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 43

% y = GetLast( x, L)

% where:

% x = input vector

% L = number of last elements to retrieve

% y = output vector

N = length(x);

if (L > N)

error('input vector too short!')

end

y = x( (N-L+1) : N );

This file should be saved as GetLast.m and may be invoked from the Matlab command prompt

by typing test = GetLast(1:2:19, 3);

then variable test will hold the vector [15 17 19] Now if you check out the variables that are currently defined using whos you will not see the

variables x, L, y, or N. These were all temporary variables created when the function ran and were deleted when the function finished. Only the value test remains. This both clears up memory and more importantly prevents a function from accidentally overwriting a variable you have set.

c) M-file example 2 This m-file takes a data vector, and checks each value to make sure it is not less than zero. If it

is, it sets it to zero. This simulates how a microcontroller, unlike a PC, usually cannot represent numbers less than 0. The m-file returns two vectors, the data output vector that has negative values set to zero and a sample number vector called index to make plotting easier.

function [y,index] = MicroSim(x)

% MicroSim replaces negative entries in a vector to zero

% usage:

% [y,index] = MicroSim(x)

% where

% x = input vector

% y = output vector

% index hold the sample number. E.g. plot result using

plot(index, y)

% setup

[nrows, ncols] = size(x);

y = x; % create the output vector

% error checking

if (ncols ~= 1 & nrows ~= 1)

error('input to MicroSim must be a vector!')

end

L = max([nrows ncols]); % length of input vector; same as

length(x)

for n=1:L % loop over the entire vector

Page 50: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 44

if y(n) < 0 % if its negative, make it equal to zero

y(n) = 0;

end

end

index = 1:L; % make the index vector

This file should be saved as MicroSim.m. If called using the vector data = [-6 -1 0 5.2 845.9]; as follows:

[y, index] = MicroSim(data);

then y will equal [0 0 0 5 846], and index will equal [1 2 3 4 5].

Page 51: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 45

4. Matlab Commands Used in Laboratory 1

Workspace commands clear x y z clears the definitions of variables x, y, and z save test x y saves the variables x and y in a file called test.mat load test loads all the variables stored in the test.mat file whos determines what variables are defined Mathematical functions real(z), imag(z) returns the real and imaginary parts of z abs(z) returns the magnitude of (possibly complex) z angle(z) returns the angle of complex z in radians round(z) returns z rounded to the nearest integer Vector functions x = linspace(0,1,100) returns a vector x of 100 numbers evenly-spaced from 0 to 1 x = [0:0.01:1] returns a vector starting at 0 and incrementing in 0.01 steps up to 1 x = zeros(3,5) creates a matrix of 3 rows and 5 columns filled with zeros x = ones(3,5) like the above but filled with ones [rows,cols] = size(m) returns the number of rows and columns in vector v rows=length(v) if v is a vector, returns its length, i.e. the number of rows if it is a row

vector or the number of columns if it is a column vector. max(v), min(v) returns the maximum or minimum value in vector v Matrix element access commands v(4) = v2(3) sets the 4th element of v to the value contained in the 3rd element of

v2. v([1 4]) = [5 10] sets the first element of vector v to 5 and the fourth to 10 v([1:4]) = [10:-1:7]; sets the first four elements of vector v to 10, 9, 8, and 7 respectively v([5:7]) = []; makes v smaller by removing the elements at positions 5, 6, and 7 v(end) = 3; sets the last element of v to 3. m([1:2],[end-1:end])=0; sets the four elements of matrix m that are in rows 1 and 2, and the

second to the last and final columns, to the value 0. m(:,3) = [] makes m smaller by removing the 3rd column Testing if(x==y) returns a 1 if scalar x equals scalar y, otherwise returns a 0 If x and y

are vectors, will compare respective elements and return a vector of 0's and 1's.

any, all If working with vectors, use if(any(x==y)) or if(all(x==y). if (x>=y) Returns 1 if x is greater or equal to y. Similar for if (x<=y). if (x~=y) Returns 1 if x is not equal to y. Flow control for i=1:10 v[i] = i/2; fills vector v with 10 values from 1/2 to 5. end

Page 52: Virginia Military Institute 5 · 2016. 9. 6. · R1 2K R2 2K R3 101K R4 C1 100K µ C2 µ V1 5 Q1 4 Q2 4 p. 0ms 3ms 6ms 9ms 12ms 15ms 18ms 21ms 24ms Computer Tools for Electrical Engineers

COL Squire EE120 Page 46

for i=1:2:10 skips over every other value in vector v disp(v[i]) end Plotting/display commands disp(m) displays vector m on the screen without assigning it to default variable

ans sprintf('Hi %g',n) if n is 4, returns the string 'Hi 4'. Usually used inside the disp

command. plot(x,y) plots the x vector against the y vector plot(x,y,'r-') makes the plot red with straight lines. Can use g,b,k for green, blue,

black. For lines can use – (straight line), -- (dashed line), or . (puts dots at each xy location but does not connect them into lines)

axis equal makes the xy aspect ratio of the plot equal, so that circles look like circles and not ellipses

title('My title') Places a title at the top of a plot window xlabel('x axis') Places the text 'x axis' below the horizontal axis of the plot ylabel('y axis') Places the text 'y axis' to the left of the plot's vertical axis