Introduction to important software and tools

advertisement
SEE1012: Introduction to Electrical Engineering
Week 10:
Introduction to important software
and tools
1. Introduction to PSpice
2. MATLAB for Engineering Applications
The materials are extracted from:
1. http://stuweb.ee.mtu.edu
2. http://www.osc.edu/
Introduction to PSpice
The Origins of SPICE
– SPICE developed in the 1970’s
• Simulation Program with Integrated
Circuit Emphasis
– Developed to save money
• Simulation of circuits, not physically
building
• Transistor sizes
–Microprocessors vs. 2N2222
This Is Now
• New user interface
• Graphical circuit
diagrams
• Variation of simulation
parameters with a few
clicks
First Look at Capture
• First window you will
see when you open
Capture
• Create a new Project
– File  New  Project
• This will open a new
window
New Project Window
• Select a project name
– PSpice Lab Simulation
• Select a project location
– C:\PSpice\{YourName}
• Select what type of
project
– Analog or Mixed A/D
• Click OK
Create PSpice Project
• This window will open
• Select the bottom
option
– Create a blank project
• Click OK
The Project Windows
• The Main Project
Window
• Two other information
windows
– Session Log Window
– Project File Window
• Our main window
– Schematic 1: Page 1
Place Parts
• Place the 5 resistors
– Using Place  Part
– Type ‘R’ in Part Field
• Place the Voltage
Source
– Using Place  Part
– Type ‘Vdc’ in Part Field
• Right click and choose
“End Mode”
Rotate and Move Resistors
• Click on the resistor
– Use ‘Ctrl+R’ to rotate
– Repeat for 4 resistors
• Move and place the
resistors in parallel
• Change the values
– Double Click on the ‘1k’
and enter ‘4k’ of the
parallel resistors
Change the Voltage and Wire
• Change DC Voltage
– Double Click on ‘0Vdc’
and enter ’16Vdc’
• Now wire the circuit
– Using Place  Wire
– Click on one node, and
‘draw’ to the other and
click again
• Right click and select
“End Mode”
Placing the Ground
• Every PSpice circuit
must have a ground
• Use the icons on the
right
– 9th icon down
• This opens the “Place
Ground” window
• Select the ‘0/Source’
• Click OK
The Completed Circuit
Simulation Profile
• Need to create a
simulation profile
– PSpice  New
Simulation Profile
• Name the profile
– DC Solution
• Click OK
Edit the Simulation Profile
• Go to the Analysis Tab
• Under the Analysis
type, choose Bias Point
– This is to find the DC
solution
• Click OK
• Ready to Simulate
Running the Simulation
• The last step is to RUN the simulation
– Do this by selecting PSpice  Run
• After running the simulation a new window
will open
– Close this window and return to the Schematic 1:
Page 1 window
• Use the “V” and “I” (and maybe “W”) icons on
the top of the screen
– For finding voltages and currents (and power)
Now You Know
• With this basic underlying knowledge
– Can change
• Resistor values
• Voltage supply values
• Resistor configuration
– Can learn
• More simulation parameters
• More components for simulation
Introduction to Matlab
MATLAB’s Appeal
• Interactive code development proceeds
incrementally; excellent development and rapid
prototyping environment
• Basic data element is the auto-indexed array
• This allows quick solutions to problems that can be
formulated in vector or matrix form
• Powerful GUI tools
• Large collection of toolboxes: collections of topicrelated MATLAB functions that extend the core
functionality significantly
Intro MATLAB
MATLAB Toolboxes
Signal & Image Processing
Math and Analysis
Signal Processing
Optimization
Image Processing
Requirements Management Interface
Communications
Statistics
Frequency Domain System Identification
Neural Network
Higher-Order Spectral Analysis
Symbolic/Extended Math
System Identification
Partial Differential Equations
Wavelet
PLS Toolbox
Filter Design
Mapping
Spline
Control Design
Control System
Data Acquisition and Import
Fuzzy Logic
Data Acquisition
Robust Control
Instrument Control
μ-Analysis and Synthesis
Excel Link
Model Predictive Control
Portable Graph Object
Intro MATLAB
Toolboxes, Software, & Links
Intro MATLAB
MATLAB System
• Language: arrays and matrices, control flow, I/O, data
structures, user-defined functions and scripts
• Working Environment: editing, variable management,
importing and exporting data, debugging, profiling
• Graphics system: 2D and 3D data visualization, animation
and custom GUI development
• Mathematical Functions: basic (sum, sin,…) to advanced
(fft, inv, Bessel functions, …)
• API: can use MATLAB with C, Fortran, and Java, in either
direction
Intro MATLAB
Online MATLAB Resources
•
•
•
•
•
•
•
www.mathworks.com/
www.mathtools.net/MATLAB
www.math.utah.edu/lab/ms/matlab/matlab.html
www.utexas.edu/its/rc/tutorials/matlab/
www.math.ufl.edu/help/matlab-tutorial/
www.indiana.edu/~statmath/math/matlab/links.html
www-h.eng.cam.ac.uk/help/tpl/programs/matlab.html
Intro MATLAB
References
Mastering MATLAB 7, D. Hanselman and B. Littlefield,
Prentice Hall, 2004
Getting Started with MATLAB 7: A Quick Introduction
for Scientists and Engineers, R. Pratap, Oxford
University Press, 2005.
Intro MATLAB
Basic Interfaces
Main MATLAB Interface
Intro MATLAB
Some MATLAB Development Windows
• Command Window: where you enter commands
• Command History: running history of commands
which is preserved across MATLAB sessions
• Current directory: Default is $matlabroot/work
• Workspace: GUI for viewing, loading and saving
MATLAB variables
• Array Editor: GUI for viewing and/or modifying
contents of MATLAB variables (openvar varname
or double-click the array’s name in the Workspace)
• Editor/Debugger: text editor, debugger; editor works
with file types in addition to .m (MATLAB “m-files”)
Intro MATLAB
MATLAB Editor Window
Intro MATLAB
MATLAB Help Window (Very Powerful)
Intro MATLAB
Command-Line Help : List of MATLAB Topics
>> help
HELP topics:
matlab\general
matlab\ops
matlab\lang
matlab\elmat
manipulation.
matlab\elfun
matlab\specfun
matlab\matfun
algebra.
matlab\datafun
matlab\polyfun
matlab\funfun
matlab\sparfun
matlab\scribe
matlab\graph2d
matlab\graph3d
matlab\specgraph
matlab\graphics
…etc...
Intro MATLAB
-
General purpose commands.
Operators and special characters.
Programming language constructs.
Elementary matrices and matrix
-
Elementary math functions.
Specialized math functions.
Matrix functions - numerical linear
-
Data analysis and Fourier transforms.
Interpolation and polynomials.
Function functions and ODE solvers.
Sparse matrices.
Annotation and Plot Editing.
Two dimensional graphs.
Three dimensional graphs.
Specialized graphs.
Handle Graphics.
Command-Line Help : List of Topic Functions
>> help matfun
Matrix functions - numerical linear algebra.
Matrix analysis.
norm
- Matrix or vector norm.
normest
- Estimate the matrix 2-norm.
rank
- Matrix rank.
det
- Determinant.
trace
- Sum of diagonal elements.
null
- Null space.
orth
- Orthogonalization.
rref
- Reduced row echelon form.
subspace
- Angle between two subspaces.
…
Command-Line Help : Function Help
>> help det
DET
Determinant.
DET(X) is the determinant of the square matrix X.
Use COND instead of DET to test for matrix
singularity.
See also cond.
Overloaded functions or methods (ones with the
same
name in other directories)
help laurmat/det.m
Reference page in Help browser
doc det
Intro MATLAB
Keyword Search of Help Entries
>> lookfor who
newton.m: % inputs: 'x' is the number whose
square root we seek
testNewton.m: % inputs: 'x' is the number
whose square root we seek
WHO
List current variables.
WHOS List current variables, long form.
TIMESTWO S-function whose output is two times
its input.
>> whos
Name
ans
fid
i
Intro MATLAB
Size
1x1
1x1
1x1
Bytes
8
8
8
Class
double
double
double
Attributes
startup.m
• Customize MATLAB’s start-up behavior
• Create startup.m file and place in:
– Windows: $matlabroot\work
– UNIX: directory where matlab command is issued
My startup.m file:
addpath e:\download\MatlabMPI\src
addpath e:\download\MatlabMPI\examples
addpath .\MatMPI
eliminates extra blank lines in output
format short g
format compact
Intro MATLAB
Variables (Arrays) and
Operators
Variable Basics
>> 16 + 24
ans =
40
no declarations needed
>> product = 16 * 23.24
product =
371.84
>> product = 16 *555.24;
>> product
product =
8883.8
Intro MATLAB
mixed data
types
semi-colon suppresses output
of the calculation’s result
Variable Basics
>> clear
clear removes all variables;
>> product = 2 * 3^3;
clear x y removes only x and
>> comp_sum = (2 + 3i) + (2 - 3i);
y
>> show_i = i^2;
complex numbers (i or j) require
>> save three_things
no special handling
>> clear
>> load three_things
>> who
save/load are used to
Your variables are:
retain/restore workspace
comp_sum product
show_i
variables
>> product
product =
54
use home to clear screen and put
>> show_i
cursor at the top of the screen
show_i =
-1
Intro MATLAB
MATLAB Data
•
The basic data type used in MATLAB is the double precision
array
• No declarations needed: MATLAB automatically allocates required
memory
• Resize arrays dynamically
• To reuse a variable name, simply use it in the left hand side
of an assignment statement
• MATLAB displays results in scientific notation
o Use File/Preferences and/or format function to change default
 short (5 digits), long (16 digits)
 format short g; format compact (my preference)
Intro MATLAB
Variables Revisited
• Variable names are case sensitive and over-written when re-used
• Basic variable class: Auto-Indexed Array
– Allows use of entire arrays (scalar, 1-D, 2-D,
etc…) as operands
– Vectorization: Always use array operands to
get best performance (see next slide)
• Terminology: “scalar” (1 x 1 array), “vector” (1 x N array), “matrix” (M
x N array)
• Special variables/functions: ans, pi, eps, inf, NaN, i,
nargin, nargout, varargin, varargout, ...
• Commands who (terse output) and whos (verbose output) show
variables in Workspace
Intro MATLAB
Vectorization Example*
>> type slow.m
tic;
x=0.1;
for k=1:199901
y(k)=besselj(3,x) +
log(x);
x=x+0.001;
end
toc;
>> slow
Elapsed time is 17.092999
seconds.
*times measured on this laptop
Intro MATLAB
>> type fast.m
tic;
x=0.1:0.001:200;
y=besselj(3,x) + log(x);
toc;
>> fast
Elapsed time is 0.551970
seconds.
Roughly 31 times faster
without use of for loop
Matrices: Magic Squares
This matrix is called a
“magic square”
Interestingly,
Durer also dated
this engraving
by placing 15
and 14 side-byside in the
magic square.
Intro MATLAB
Durer’s Matrix: Creation
» durer1N2row = [16 3 2 13; 5 10 11
8];
» durer3row = [9 6 7 12];
» durer4row = [4 15 14 1];
» durerBy4 =
[durer1N2row;durer3row;durer4row];
» durerBy4
durerBy4 =
16
5
9
4
Intro MATLAB
3
10
6
15
2
11
7
14
13
8
12
1
Easier Way...
durerBy4 =
16
3
5
10
9
6
4
15
2
11
7
14
13
8
12
1
» durerBy4r2 = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
durerBy4r2 =
16
5
9
4
Intro MATLAB
3
10
6
15
2
11
7
14
13
8
12
1
Multidimensional Arrays
>> r = randn(2,3,4) % create a 3 dimensional array filled
with
normally distributed random numbers
“%” sign precedes comments,
r(:,:,1) =
MATLAB ignores the rest of the line
-0.6918
1.2540
-1.4410
0.8580
-1.5937
0.5711
randn(2,3,4): 3 dimensions, filled
r(:,:,2) =
with normally distributed random
-0.3999
0.8156
1.2902 numbers
0.6900
0.7119
0.6686
r(:,:,3) =
1.1908
-0.0198
-1.6041
-1.2025
-0.1567
0.2573
r(:,:,4) =
-1.0565
-0.8051
0.2193
1.4151
0.5287
-0.9219
Intro MATLAB
Character Strings
>> hi = ' hello';
>> class = 'MATLAB';
>> hi
hi =
hello
>> class
class =
MATLAB
>> greetings = [hi class]
greetings =
helloMATLAB
>> vgreetings = [hi;class]
vgreetings =
hello
MATLAB
Intro MATLAB
concatenation with blank or with “,”
semi-colon: join vertically
Character Strings as Arrays
>> greetings
greetings =
helloMATLAB
>> vgreetings = [hi;class]
vgreetings =
hello
MATLAB
note deleted space
>> hi = 'hello'
at
hi =
beginning of word;
hello
results in error
>> vgreetings = [hi;class]
??? Error using ==> vertcat
CAT arguments dimensions are not consistent.
Intro MATLAB
String Functions
yo =
Hello
Class
>> ischar(yo)
ans =
1
>> strcmp(yo,yo)
ans =
1
Intro MATLAB
returns 1 if argument is a character
array and 0 otherwise
returns 1 if string arguments are the
same and 0 otherwise; strcmpi ignores
case
Set Functions
Arrays are ordered sets:
>> a = [1 2 3 4 5]
a =
1
2
3
>> b = [3 4 5 6 7]
b =
3
4
5
>> isequal(a,b)
ans =
0
>> ismember(a,b)
ans =
0
0
1
Intro MATLAB
4
6
5
7
returns true (1) if arrays are the same
size and have the same values
returns 1 where a is in b
and 0 otherwise
1
1
Matrix Operations
>> durer = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
durer =
16
5
9
4
3
10
6
15
2
11
7
14
13
8
12
1
MATLAB also has
magic(N) (N >
2)
function
>> % durer's matrix is "magic" in that all rows,
columns,
>> % and main diagonals sum to the same number
>> column_sum = sum(durer) % MATLAB operates columnwise
column_sum =
34
34
Intro MATLAB
34
34
Transpose Operator
>> % to get the row sums, we'll use the transpose
operator
>> % (an apostrophe)
>> durer'
ans =
16
5
3
10
2
11
13
8
9
6
7
12
4
15
14
1
>> row_sums = sum(durer')'
row_sums =
34
34
34
34
Intro MATLAB
Diagonal Elements
>> durer
durer =
16
5
9
4
3
10
6
15
2
11
7
14
13
8
12
1
>> diag(durer) % diag plucks out the diagonal elements
ans =
16
10
7
1
>> sum(diag(durer))
ans =
34
Intro MATLAB
The Other Diagonal…
>> durer
durer =
16
5
9
4
3
10
6
15
2
11
7
14
13
8
12
1
>> fliplr(durer) % “flip left-right”
ans =
13
2
3
16
8
11
10
5
12
7
6
9
1
14
15
4
>> sum(diag(fliplr(durer)))
ans =
34
Intro MATLAB
Matrix Subscripting
>> durer
durer =
16
5
9
4
3
10
6
15
2
11
7
14
13
8
12
1
>> diag_sum = durer(1,1) + durer(2,2) + durer(3,3)
diag_sum =
33
>> durer(4,4) = pi
durer =
16.0000
3.0000
2.0000
13.0000
5.0000
10.0000
11.0000
8.0000
9.0000
6.0000
7.0000
12.0000
4.0000
15.0000
14.0000
3.1416
>> durer(4,4) = 1
Intro MATLAB
Colon Operator (Vector Creation)
>> 1:5 % use the colon operator to create row
vectors
ans =
1
2
3
4
5
>> 1:0.9:6 % you can vary the increment (0.9 in
this case)
ans =
1.0000
1.9000
2.8000
3.7000
4.6000
5.5000
The last element is always less than or equal to
the upper limit
Intro MATLAB
Colon Operator (Indexing)
>> sum(durer(1:3,4)) % sums first three
% elements of column 4
ans =
33
>> sum(durer(:,end)) % a lone colon is ALL
% elements, end is
% the last element
ans =
34
Intro MATLAB
The “Dot Operator”
• By default and whenever possible MATLAB will
perform true matrix operations (+ - *). The operands
in every arithmetic expression are considered to be
matrices.
• If, on the other hand, the user wants the scalar
version of an operation a “dot” must be put in front
of the operator, e.g., .*. Matrices can still be the
operands but the mathematical calculations will be
performed element-by-element.
• A comparison of matrix multiplication and scalar
multiplication is shown on the next slide.
Intro MATLAB
Dot Operator Example
>> A = [1 5 6; 11 9 8; 2 34 78]
A =
1
5
6
11
9
8
2
34
78
>> B = [16 4 23; 8 123 86; 67 259 5]
B =
16
4
23
8
123
86
67
259
5
Intro MATLAB
Dot Operator Example (cont.)
>> C = A * B
C =
458
784
5530
% “normal” matrix multiply
>> CDOT = A .* B
CDOT =
16
88
134
Intro MATLAB
2173
3223
24392
483
1067
3360
% element-by-element
20
1107
8806
138
688
390
Two Division Operators
• Right divide (familiar version) a/b
– What happens: a is divided by b
– Right operand “goes into” left operand
• Left divide a\b
– What happens: b is divided by a
– Left operand “goes into” right operand
– Behavior depends on operands (scalar vs. matrix)
• Both operators work with matrices (of course). More later
on what is actually calculated …
• Comparison of the use of / and \ on next slide
Intro MATLAB
Using the Division Operators
>> x = 53.0;
>> y = 22.5;
>> x/y
ans = 2.3556
>> x\y
For matrix operands, A\B is the solution
to
ans = 0.4245
Ax = B obtained by Gaussian
elimination.
>> (x/y)^(-1)
ans = 0.4245
Read “Arithmetic Operators + - * / \ ^ ’
”
in “MATLAB Function Reference”:
Help  Search for: division
Intro MATLAB
Easy 2-D Graphics
>> x = [0: pi/100: pi]; % [start: increment: end]
>> y = sin(x);
>> plot(x,y), title('Simple Plot')
Intro MATLAB
Adding Another Curve
>> z = cos(x);
>> plot(x,y,'g.',x,z,'b-.'),title('More complicated')
Line color, style, marker type,
all within single quotes; type
>> doc LineSpec
for all available line properties
Intro MATLAB
Lab 1
•
•
•
•
•
•
Create a row vector called X whose elements are the integers 1 through 9.
Create another row vector called Temp whose elements are:
15.6 17.5 36.6 43.8 58.2 61.6 64.2 70.4 98.8
These data are the result of an experiment on heat conduction through an iron bar.
The array X contains positions on the bar where temperature measurements were
made. The array Temp contains the corresponding temperatures.
Make a 2-D plot with temperature on the y-axis and position on the x-axis.
The data shown in your plot should lie along a straight line (according to physics) but
don’t because of measurement errors. Use the MATLAB polyfit function to fit the
best line to the data (use >> hold on; for multiple plots in same figure). In other
words use polyfit to determine the coefficients a and b of the equation
T = ax + b
Lastly, we can calculate a parameter called chi-square (χ2) that is a measure of how
well the data fits the line. Calculate chi-square by running the MATLAB command that
does the following matrix multiplication:
>> (Temp-b-a*X)*(Temp-b-a*X)'
Intro MATLAB
Lab 2
•
•
•
•
•
•
Write a MATLAB command that will generate a column vector called
theta. theta should have values from –2π to 2π in steps of π/100.
Generate a matrix F that contains values of the following functions in the
columns indicated:
Column 1: cos(θ)
Column 2: cos(2θ)(1 + sin(θ2)
Column 3: e -0.1|θ|
Evaluate each of the above functions for the θ values in the theta
vector from above.
Plot each of the columns of F against theta. Overlay the three plots,
using a different color for each.
Create a new column vector called maxVect that contains the largest of
the three functions above for each theta. Plot maxVect against
theta.
Create a column vector called maxIndex that has the column number
of the maximum value in that row.
Intro MATLAB
Programming
Outline
• MATLAB m-file Editor
– To start: click
icon or enter edit command in
Command Window, e.g., >> edit test.m
• Scripts and Functions
• Decision Making/Looping
– if/else
– switch
– for and while
• Running Operating System Commands
Intro MATLAB
m-file Editor Window
You can save and run the
file/function/script in one
step by clicking here
Tip: semi-colons suppress printing, commas (and
semi-colons) allow multiple commands on one line,
and 3 dots (…) allow continuation of lines without
execution
Intro MATLAB
Scripts and Functions
• Scripts do not accept input arguments, nor do they
produce output arguments. Scripts are simply MATLAB
commands written into a file. They operate on the existing
workspace.
• Functions accept input arguments and produce output
variables. All internal variables are local to the function
and commands operate on the function workspace.
• A file containing a script or function is called an m-file
• If duplicate functions (names) exist, the first in the search
path (from path command) is executed.
Intro MATLAB
Functions – First Example
function [a b c] = myfun(x, y) Write these two lines to a file
myfun.m and save it on MATLAB’s
b = x * y; a = 100; c = x.^2;
path
>> myfun(2,3)
% called with zero
outputs
ans =
100
>> u = myfun(2,3)
% called with one output
u =
100
>> [u v w] = myfun(2,3) % called with all outputs
u =
Any return value which is not stored
100
in an output variable is simply
v =
discarded
6
w =
4
Intro MATLAB
THE END
Download