week 10: introduction to important software and tools see1012: introduction to electrical...

Download Week 10: Introduction to important software and tools SEE1012: Introduction to Electrical Engineering

If you can't read please download the document

Upload: william-walker

Post on 18-Jan-2018

221 views

Category:

Documents


0 download

DESCRIPTION

Introduction to PSpice

TRANSCRIPT

Week 10: Introduction to important software and tools SEE1012: Introduction to Electrical Engineering 1. Introduction to PSpice 2. MATLAB for Engineering Applications The materials are extracted from: Introduction to PSpice The Origins of SPICE SPICE developed in the 1970s 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 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 New Project Window 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 9 th 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 Intro MATLAB MATLABs 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 topic- related MATLAB functions that extend the core functionality significantly Intro MATLAB MATLAB Toolboxes Signal & Image Processing Signal Processing Image Processing Communications Frequency Domain System Identification Higher-Order Spectral Analysis System Identification Wavelet Filter Design Control Design Control System Fuzzy Logic Robust Control -Analysis and Synthesis Model Predictive Control Math and Analysis Optimization Requirements Management Interface Statistics Neural Network Symbolic/Extended Math Partial Differential Equations PLS Toolbox Mapping Spline Data Acquisition and Import Data Acquisition Instrument Control Excel Link 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-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. Basic Interfaces Intro MATLAB 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 arrays 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 - General purpose commands. matlab\ops - Operators and special characters. matlab\lang - Programming language constructs. matlab\elmat - Elementary matrices and matrix manipulation. matlab\elfun - Elementary math functions. matlab\specfun - Specialized math functions. matlab\matfun - Matrix functions - numerical linear algebra. matlab\datafun - Data analysis and Fourier transforms. matlab\polyfun - Interpolation and polynomials. matlab\funfun - Function functions and ODE solvers. matlab\sparfun - Sparse matrices. matlab\scribe - Annotation and Plot Editing. matlab\graph2d - Two dimensional graphs. matlab\graph3d - Three dimensional graphs. matlab\specgraph - Specialized graphs. matlab\graphics - Handle Graphics. etc... 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. Intro MATLAB 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 Size Bytes Class Attributes ans 1x1 8 double fid 1x1 8 double i 1x1 8 double Intro MATLAB startup.m Customize MATLABs 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 format short g format compact eliminates extra blank lines in output Variables (Arrays) and Operators Intro MATLAB Variable Basics no declarations needed mixed data types semi-colon suppresses output of the calculations result >> ans = 40 >> product = 16 * product = >> product = 16 *555.24; >> product product = Intro MATLAB Variable Basics complex numbers ( i or j ) require no special handling clear removes all variables; clear x y removes only x and y clear removes all variables; clear x y removes only x and y save / load are used to retain/restore workspace variables save / load are used to retain/restore workspace variables >> clear >> product = 2 * 3^3; >> comp_sum = (2 + 3i) + (2 - 3i); >> show_i = i^2; >> save three_things >> clear >> load three_things >> who Your variables are: comp_sum product show_i >> product product = 54 >> show_i show_i = use home to clear screen and put cursor at the top of the screen 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: y(k)=besselj(3,x) + log(x); x=x+0.001; end toc; >> slow Elapsed time is seconds. *times measured on this laptop >> type fast.m tic; x=0.1:0.001:200; y=besselj(3,x) + log(x); toc; >> fast Elapsed time is seconds. Roughly 31 times faster without use of for loop Intro MATLAB Matrices: Magic Squares This matrix is called a magic square Interestingly, Durer also dated this engraving by placing 15 and 14 side-by- side in the magic square. Intro MATLAB Durers Matrix: Creation durer1N2row = [ ; ]; durer3row = [ ]; durer4row = [ ]; durerBy4 = [durer1N2row;durer3row;durer4row]; durerBy4 durerBy4 = Intro MATLAB Easier Way... durerBy4 = durerBy4r2 = [ ; ; ; ] durerBy4r2 = Intro MATLAB Multidimensional Arrays >> r = randn(2,3,4) % create a 3 dimensional array filled with normally distributed random numbers r(:,:,1) = r(:,:,2) = r(:,:,3) = r(:,:,4) = randn(2,3,4) : 3 dimensions, filled with normally distributed random numbers % sign precedes comments, MATLAB ignores the rest of the line 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 semi-colon: join vertically concatenation with blank or with , Intro MATLAB Character Strings as Arrays >> greetings greetings = helloMATLAB >> vgreetings = [hi;class] vgreetings = hello MATLAB >> hi = 'hello' hi = hello >> vgreetings = [hi;class] ??? Error using ==> vertcat CAT arguments dimensions are not consistent. note deleted space at beginning of word; results in error note deleted space at beginning of word; results in error Intro MATLAB yo = Hello Class >> ischar(yo) ans = 1 >> strcmp(yo,yo) ans = 1 String Functions returns 1 if argument is a character array and 0 otherwise 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 returns 1 if string arguments are the same and 0 otherwise; strcmpi ignores case Intro MATLAB Set Functions Arrays are ordered sets: >> a = [ ] a = >> b = [ ] b = >> isequal(a,b) ans = 0 >> ismember(a,b) ans = returns true (1) if arrays are the same size and have the same values returns 1 where a is in b and 0 otherwise Intro MATLAB >> durer = [ ; ; ; ] durer = >> % durer's matrix is "magic" in that all rows, columns, >> % and main diagonals sum to the same number >> column_sum = sum(durer) % MATLAB operates column- wise column_sum = Matrix Operations MATLAB also has magic(N) (N > 2) function MATLAB also has magic(N) (N > 2) function Intro MATLAB Transpose Operator >> % to get the row sums, we'll use the transpose operator >> % (an apostrophe) >> durer' ans = >> row_sums = sum(durer')' row_sums = 34 Intro MATLAB Diagonal Elements >> durer durer = >> diag(durer) % diag plucks out the diagonal elements ans = >> sum(diag(durer)) ans = 34 Intro MATLAB The Other Diagonal >> durer durer = >> fliplr(durer) % flip left-right ans = >> sum(diag(fliplr(durer))) ans = 34 Intro MATLAB Matrix Subscripting >> durer durer = >> diag_sum = durer(1,1) + durer(2,2) + durer(3,3) diag_sum = 33 >> durer(4,4) = pi durer = >> durer(4,4) = 1 Intro MATLAB Colon Operator (Vector Creation) >> 1:5 % use the colon operator to create row vectors ans = >> 1:0.9:6 % you can vary the increment (0.9 in this case) ans = 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; ; ] A = >> B = [ ; ; ] B = Intro MATLAB Dot Operator Example (cont.) >> C = A * B % normal matrix multiply C = >> CDOT = A.* B % element-by-element CDOT = Intro MATLAB 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 = >> x\y ans = >> (x/y)^(-1) ans = For matrix operands, A\B is the solution to Ax = B obtained by Gaussian elimination. 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 Line color, style, marker type, all within single quotes; type >> doc LineSpec for all available line properties Line color, style, marker type, all within single quotes; type >> doc LineSpec for all available line properties >> z = cos(x); >> plot(x,y,'g.',x,z,'b-.'),title('More complicated') 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: 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 dont 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. Programming Intro MATLAB 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 Outline Intro MATLAB 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 m-file Editor Window 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 function [a b c] = myfun(x, y) b = x * y; a = 100; c = x.^2; >> 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 = 100 v = 6 w = 4 Functions First Example Write these two lines to a file myfun.m and save it on MATLABs path Any return value which is not stored in an output variable is simply discarded THE END