introduction to simulation language

257
Introduction to Simulation language

Upload: keelia

Post on 23-Feb-2016

45 views

Category:

Documents


3 download

DESCRIPTION

Introduction to Simulation language. What is Simulation?. A Simulation of a system is the operation of a model, which is a representation of that system. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction  to  Simulation language

Introduction to

Simulation language

Page 2: Introduction  to  Simulation language

What is Simulation?

Introduction to PSpice 2

A Simulation of a system is the operation of a model, which is a representation of that system.

The model is amenable to manipulation which would be impossible, too expensive, or too impractical to perform on the system which it portrays.

The operation of the model can be studied, and, from this, properties concerning the behavior of the actual system can be inferred.

Page 3: Introduction  to  Simulation language

GEN. PURPOSE LANGUAGES USED FOR SIMULATION

Introduction to PSpice 3

FORTRAN– Probably more models than any other

language.PASCAL

– Not as universal as FORTRANMODULA

– Many improvements over PASCALADA

– Department of Defense attempt at standardization

C, C++– Object-oriented programming language

Page 4: Introduction  to  Simulation language

Simulation tools

Introduction to PSpice 4

(For EE-2240)

• PSPICE

• MATLAB

• SIMULINK

Page 5: Introduction  to  Simulation language

Introduction to PSpice 5

Introduction to PSpice

Simulation Software

Page 6: Introduction  to  Simulation language

The Origins of SPICE

Introduction to PSpice 6

–SPICE developed in the 1970’s• Simulation Program with Integrated Circuit Emphasis

–Developed to save money• Simulation of circuits, not physically building•Can perform DC level, AC frequency response and transient time domain simulations.

Page 7: Introduction  to  Simulation language

Introduction to PSpice 7

Steps in simulating circuit using PSpice

1 Convert your circuit into a netlist. Save your netlist using text editor with extension .cir

2 Run PSpice and simulate your .cir file

3 Obtain the results from your output file

Page 8: Introduction  to  Simulation language

Introduction to PSpice 8

Examples – DC analysis

This is how you write a PSpice netlist for the circuit: Test 1i1 0 1 dc 1.5r1 1 0 100r2 1 2 150r3 2 0 250.dc i1 1.5 1.5 1.print dc v(1) v(2) i(r1) i(r2).end

Title statement

Data statement

Control statement

Output statement End statement

1

Page 9: Introduction  to  Simulation language

Introduction to PSpice 9

2Run PSpice and simulate your .cir file

Page 10: Introduction  to  Simulation language

Introduction to PSpice 10

3 Display the output

This depends on what you write in the output statement

Page 11: Introduction  to  Simulation language

Introduction to PSpice 11

Examples

Page 12: Introduction  to  Simulation language

12

Steps in simulating circuit using PSpice

Input file (*.cir) containing

Netlist PSPICE

**** 07/21/10 10:19:34 *********** Evaluation PSpice (Nov 1999) ************** Test 1

**** CIRCUIT DESCRIPTION

******************************************************************************

i1 0 1 dc 1.5r1 1 0 100r2 1 2 150r3 2 0 250.dc i1 1.5 1.5 1.print dc v(1) v(2) i(r1) i(r2).end

**** 07/21/10 10:19:34 *********** Evaluation PSpice (Nov 1999) ************** Test 1

**** DC TRANSFER CURVES TEMPERATURE = 27.000 DEG C

******************************************************************************i1 V(1) V(2) I(r1) I(r2)

1.500E+00 1.200E+02 7.500E+01 1.200E+00 3.000E-01

JOB CONCLUDED

TOTAL JOB TIME .02

Output file

Circuits

Page 13: Introduction  to  Simulation language

Use of Schematic

Introduction to PSpice 13

Create Schematic circuit using drawing (Using “Schematic” or “Capture”)

Simulate the circuit

(PSPICE)

Plot and analyze the results

Page 14: Introduction  to  Simulation language

Use of Schematic (Contd.)

• Use Schematic capture • to enter schematic and set up simulation parameters before running

• PSpice (simulation engine) • and then look at results in

• Probe

Also available at CERN:• Parts (modelling program)• Stimulus Editor (to produce “custom” voltage/current/digital sources)• Optimizer (can automatically vary circuit component values to satisfy

design criteria)

Introduction to PSpice 14

Page 15: Introduction  to  Simulation language

PSPICE Graphical Tutorial

Page 16: Introduction  to  Simulation language

Go to: Start: All Programs: Electrical Apps: Orcad Family… : PSpice Design Manager

Page 17: Introduction  to  Simulation language

It will look like this:

Page 18: Introduction  to  Simulation language

Click on: File : New Workspace

Page 19: Introduction  to  Simulation language

Give your New Workspace a Names and Location

Page 20: Introduction  to  Simulation language

It will then look like this:

Then click here

Page 21: Introduction  to  Simulation language

An area to draw your circuit will open up

Page 22: Introduction  to  Simulation language

Click on Draw: Get New Part

Page 23: Introduction  to  Simulation language

This window will then open up

Page 24: Introduction  to  Simulation language

Enter a part name: R, C, L, etc…

All related parts will list here: select the one you wantIt’s symbol will then appear here

Page 25: Introduction  to  Simulation language

Click Place and put the part(s) where you want it or them

Page 26: Introduction  to  Simulation language

Click on the part value to change its value:

Page 27: Introduction  to  Simulation language

Then select a DC voltage supply and place it

Page 28: Introduction  to  Simulation language

Draw the wires to connect all the parts

Page 29: Introduction  to  Simulation language

Your circuit will look something like this:

Page 30: Introduction  to  Simulation language

Click on the wires to label the circuit nodes: call the ground wire “0”

Page 31: Introduction  to  Simulation language

Now mark the circuit nodes of interest with Voltage Level Markers

Page 32: Introduction  to  Simulation language

Your circuit will look something like this:

Page 33: Introduction  to  Simulation language

Click on Analysis: Setup

Page 34: Introduction  to  Simulation language

For DC circuit analysis, enable: “Bias Point Detail”

Page 35: Introduction  to  Simulation language

Select Analysis: Create Netlist (correct circuit layout if any errors found)

Page 36: Introduction  to  Simulation language

Select Analysis: Simulate to analyze the circuit

Page 37: Introduction  to  Simulation language

This window tells you how the simulation went

Page 38: Introduction  to  Simulation language

Go to your workspace directory and click on the Output File

Page 39: Introduction  to  Simulation language

Scroll down to you find the voltages for the nodes you marked in the circuit. The voltages are referenced to node “0.”

Page 40: Introduction  to  Simulation language

This time, replace the DC voltage source with a time varying voltage source, such as VPULSE

Page 41: Introduction  to  Simulation language

Put it in the circuit and click on it to select it’s parameters

Page 42: Introduction  to  Simulation language

Here I selected the constant DC and AC values to be zero, the initial voltage level (V1) to be zero, the final voltage level (V2) to be 10V, the time delay (TD) to be 1us and the rise time (TR) to be 10us. I left the other options blank

Page 43: Introduction  to  Simulation language

Under Analysis Setup, enable “Transient…” and click on it

Keep the “Bias Point Detail” enabled too

Page 44: Introduction  to  Simulation language

Set the Transient Analysis Final Time to 100us

Page 45: Introduction  to  Simulation language

Run the Simulation and these result will appear:

A plot of the voltages at all the marked nodes over the transient analysis time (0s to 100us)

Play with this window to adjust display time and what signals are displayed

Page 46: Introduction  to  Simulation language

PSPICE Reference Manuals

• Look in C:\Program Files\Orcad\Document

• pspug.pdf• pspqrc.pdf• PSpcRef.pdf• psp_sug.pdf

Page 47: Introduction  to  Simulation language

Set-up VAC source

• Set-up VAC*• DC=0

• used to find initial DC solution

• ACMAG=1• source p-to-p value

during AC analysis• ACPHASE=0

• reference for phase measurements

Introduction to PSpice 47*VSIN can also be used for AC analysis - see Appendix 1 for set-up explanation

Page 48: Introduction  to  Simulation language

Set-up AC analysis and Probe

• From Menu• Analysis/Setup…

• or Toolbar -

• Click “AC Sweep”• Enter as shown• Click “OK”

Introduction to PSpice 48

Page 49: Introduction  to  Simulation language

Set-up Probe and Run Analysis

• Set-up Probe• From Menu

• Analysis/Probe Setup…

• Under Data Collection tab, select “All”

N.B. other options allow to limit size of .dat file

• Run Analysis• From Menu

• Analysis/Simulate

• From keyboard• F11

• From Toolbar -Introduction to PSpice 49

Page 50: Introduction  to  Simulation language

Some Probe commands • Add Trace

• • Trace/Add• Insert

reduce traces shown,use voltage markers

• Add Y-axis• Plot/Add Y-axis• Ctrl-Y

N.B “>>” indicates the active axis

• Display manipulation functions•

or

• from the menu• View/Fit,In,Out,Areaor

• from the keyboard• Ctrl N,I,O,A

• To re-scale axes• double-click on any axis

or

• Plot X(Y)-Axis Settings...

Introduction to PSpice 50

Page 51: Introduction  to  Simulation language

Exercise: Measure the f3dB point of v_out using the

cursors

• In Probe:• Trace/Add,

DB(V(v_out))• To make cursors

active - select

• Place one cursor on nominal 0dB point

• Move other cursor until “dif” shows difference of 3dB

Introduction to PSpice 51

Page 52: Introduction  to  Simulation language

Exercise: Measure the f3dB point of v_out using a goal

function

• N.B. to see a detailed explanation of this goal function and its parameters, select:• Trace/Goal Functions, LPBW, View

• The g.f. can also be evaluated from this window (select Eval instead of View)Introduction to PSpice 52

In Probe:Trace/Eval Goal Function…

Select: LPBW(1,db_level)

Select: V(v_out)

Enter 3 from the keyboard

Click on OK

Page 53: Introduction  to  Simulation language

Adding parameters

• Change C1 value to {c_val}N.B. name is unimportant but { } are mandatory

• Add a PARAM symbol (Draw/Get New Part…/ Param)

• Set up NAME1 and VALUE1 PARAM values (double-click on the symbol).

• Click OK Introduction to PSpice 53

Page 54: Introduction  to  Simulation language

Set-up Parametric sweep

• Setup a Parametric sweep (Analysis/Setup…/Parametric)

• Click OK

• Run AC analysis

Introduction to PSpice 54

Page 55: Introduction  to  Simulation language

Parametric analysis results • When Probe opens, it will

(typically) show:

• The analysis results are split into “sections”. There is one section for each value of parametric sweep

• Click on OK

Introduction to PSpice 55

Page 56: Introduction  to  Simulation language

Exercises - Performance Analysis

• Select Trace/Add. Plot DB(V(v_out))• Select Trace/Performance Analysis (or from

the toolbar).• Click OK

- a new window appears. The X-axis is R, the parameter varied

• Select Trace/Add. Plot (LPBW(V(v_out),3))• Select Plot/Add Plot• Select Trace/Add. Plot 1/(LPBW(V(v_out),3))Introduction to PSpice 56

Page 57: Introduction  to  Simulation language

Transient.sch (1)• Load transient.sch• Complete by adding

IPWL*

(IPWL is a Piece Wise Linear current source)

Set-up IPWL by adding (time,current) points:(T1=0, I1=0),(T2=10ms, I2=0),(T3=10.1ms, I3=1)

Introduction to PSpice 57*to set-up the ISTIM part, see appendix 3

Page 58: Introduction  to  Simulation language

Set-up transient and exercises• Set-up transient run:

• Print step: 100ms• final time: 20s

• What range of values of R1 satisfies:

• risetime I(L1) < 2s• overshoot I(L1) < 10% ?

58

Hints:– Range is somewhere between 0.4 and 1.5 Ohms (set-up Parametric Analysis

in Schematics using Analysis/Setup…/Parametric…)– In Probe, select Trace/Performance Analysis… , click OK– Use GenRise() and Overshoot() goal functions

Page 59: Introduction  to  Simulation language

ExercisesExercise 1• Design a “perfect” non-inverting voltage op-amp using E (voltage-

controlled voltage-source). Verify using VPULSE (appendix 2) and transient analysis

• Design a “perfect” non-inverting voltage op-amp using A(nalog) B(ehavioral) M(odelling) parts (found in ABM library)

• Design an imperfect non-inverting voltage op-amp (output limited to ”supply voltage”).

59

Exercise 2 Design an attenuator with input

parameters IMP and ATT. Calculate values for R1,R2 such that:

– v_out = v_in - ATT dB – The impedance seen from RS =

IMP– Add parameter checking

Page 60: Introduction  to  Simulation language

Digital simulation (1)

• “PSpice” is two simulators - one analogue and one digital• The analogue one solves Kirchoff’s laws • The digital one uses Boolean arithmetic

• The digital simulator has an extensive library of “characterised” digital parts - these are mostly behavioural models only (which includes timing information)

• To simulate “real” (analogue) input/output behaviour, find the transistor-level circuits

• proprietary information• very slow simulation speeds

Introduction to PSpice 60

Page 61: Introduction  to  Simulation language

Digital simulation (2)

• Digital device libraries are usually specified in families.• Each device has its own timing model (typical, min.,

max. times specified here)• Each device has an I/O model. This will be shared by all

devices in the same logic family• The I/O model includes a nominal impedance representation for

each I/O pin. It also includes information on which type of AtoD and DtoA converter to use for each device. These converters are powered off the supplies defined by IPIN(supply).

• The converters are ONLY USED when interfacing between the analogue and digital simulators!

Introduction to PSpice 61

Page 62: Introduction  to  Simulation language

Digpower.sch (see Appendices 4, 5)

Introduction to PSpice 62

Page 63: Introduction  to  Simulation language

Digital Setup

• Timing mode• leave on Typical

• Flip-flop initialization• depends on circuit

• Default Interface• leave on Level 1

Introduction to PSpice 63

If you have lots of “unimportant” digital warnings - set Default A/D Interface to Level 2 (see Appendix 6)

Page 64: Introduction  to  Simulation language

Setting Initial Conditions

• Initial conditions can be set in the analogue simulator using:

• IC on components• Setpoints• Nodeset• Save/Load Bias Point (also see Appendix 7)

Introduction to PSpice 64

Page 65: Introduction  to  Simulation language

Appendices

• 1) Setup VSIN• 2) Setup VPULSE • 3) Setup ISTIM • 4) Default digital power supplies • 5) Changing CMOS power supplies• 6) Default A/D interface definitions• 7) Setting Initial ConditionsIntroduction to PSpice 65

Page 66: Introduction  to  Simulation language

Appendix 1 - Setup VSIN

• Set-up VSIN • DC=0• AC=1*• VOFF=2• VAMPL=2• FREQ=5• TD=1• DF=1• PHASE=45*AC Analysis only

Introduction to PSpice 66

Page 67: Introduction  to  Simulation language

Appendix 2 - Setup VPULSE

• Example • DC=0• AC=1*• V1=1• V2=4• TD=1• TR=1• TF=1• PW=2• PER=6*AC Analysis onlyIntroduction to PSpice 67

Page 68: Introduction  to  Simulation language

Appendix 3 - Setup ISTIM

• Double click on Stimulus=• Enter name test• Double click on ISTIM body to

open STMED - Select PWL

• Double-click on axis• Set X-axis to range 10.1ms,

resolution 0.1ms• Set Y-axis to range 1, resolution 0.2• Enter (time,value) points using the

“pencil” :

(t1=0, I1=0), (t2=10ms, I1=0), (t3=10.1ms, I3=1)

• Save and exit Stimulus Editor N.B this saves the stimulus “test” in

transient.stl 68

Page 69: Introduction  to  Simulation language

Appendix 4 - Default digital power supplies

• Most digital parts and stimulii already have a default power supply.

• The four default power supplies provided in the model library are:

– DIGIFPWR (TTL)– CD4000_PWR (CD4000 series

CMOS)– ECL_10K_PWR (ECL10K)– ECL_100K_PWR (ECL 100K).

Introduction to PSpice 69

Page 70: Introduction  to  Simulation language

Introduction to Matlab

Page 71: Introduction  to  Simulation language

Outline:What is Matlab?• Matlab Screen• Variables, array, matrix, indexing • Operators (Arithmetic, relational, logical )• Display Facilities• Flow Control• Using of M-File• Writing User Defined Functions• Conclusion

Page 72: Introduction  to  Simulation language

What is MATLAB?

• MATLAB is a simple programming language with its own extensive library of mathematical and graphical subroutines

• It integrates computation and graphics in one easy to use interface

• MATLAB stands for MATrix LABoratory.• MATLAB is very extendable. There are many

add-ons (toolboxes) for specific requirements

Introduction to PSpice 72

Page 73: Introduction  to  Simulation language

What is Matlab?• Matlab is basically a high level language which has many specialized toolboxes for making things easier for us

• How high?

Assembly

High Level Languages such as

C, Pascal etc.

Matlab

Page 74: Introduction  to  Simulation language

What are we interested in?• Matlab is too broad for our purposes in this

course.• The features we are going to require is

Matlab

CommandLinem-files

functions

mat-files

Command execution like DOS command

window

Series of Matlab

commands

InputOutput

capability

Data storage

/ loading

Page 75: Introduction  to  Simulation language

           Start menu       Matlab       MATLAB

>> Ctrl+C % stop Matlab from running>> clc % clear screen

Page 76: Introduction  to  Simulation language

Special characters

• >> % default command prompt • %  % comment - MATLAB simply ignores

anything to the right of this sign (till the end of the line).

>> % my comment• ; % semicolon at the end of the line will

prevent MATLAB from echoing the information you type on the screen. 

>> a=20>> B=20;

Page 77: Introduction  to  Simulation language

Creating Variables

• Matlab as a calculator:• >>2+5• >>7*10+8• >>5^2• ‘ans’ - "answer", used in MATLAB as the default

variable.

Page 78: Introduction  to  Simulation language

Defining Your Own Variables

• When Matlab comes across a new variable name - it automatically creates it. 

• Begins with a LETTER, e.g., A2z. • Can be a mix of letters, digits, and underscores (e.g.,

vector_A, but not vector-A)• Not longer than 31 characters. • No spaces • Different mixes of capital and small letters = different

variables. For example: "A_VaRIAbLe", "a_variable", "A_VARIABLE", and "A_variablE

• >> String=‘this is a string’

Page 79: Introduction  to  Simulation language

Some Built-in functions• mean(A):mean value of a vector• max(A), min (A): maximum and minimum. • sum(A): summation.• sort(A): sorted vector• median(A): median value• std(A): standard deviation. • det(A) : determinant of a square matrix • dot(a,b): dot product of two vectors• Cross(a,b): cross product of two vectors• Inv(A): Inverse of a matrix A

Page 80: Introduction  to  Simulation language

Indexing MatricesGiven the matrix:

Then:

A(1,2) = 0.6068

A(3) = 0.6068

A(:,1) = [0.9501

0.2311 ]

A(1,2:3)=[0.6068 0.4231]

A = 0.9501 0.6068 0.4231 0.2311 0.4860 0.2774

Aij,i 1...m, j 1...n

index (i 1)m j

m

n

1:m

Page 81: Introduction  to  Simulation language

Listing & Clearing Variables

<< whos

<< clear, clear all %clear variables from memory

<< a=10<< b = 20<< the_average = (a + b ) / 2

Page 82: Introduction  to  Simulation language

Matlab Screen• Command Window

• type commands

• Current Directory• View folders and m-files

• Workspace• View program variables• Double click on a variable to see it in the Array Editor

• Command History• view past commands• save a whole session using diary

Page 83: Introduction  to  Simulation language

Variables• No need for types. i.e.,

• All variables are created with double precision unless specified and they are matrices.

• After these statements, the variables are 1x1 matrices with double precision

int a;double b;float c;

Example:>>x=5;>>x1=2;

Page 84: Introduction  to  Simulation language

MATLAB symbols

>> prompt. . . continue statement on next line, separate statements and data% start comment which ends at end of line; (1) suppress output

(2) used as a row separator in a matrix : specify range

84

Page 85: Introduction  to  Simulation language

MATLAB Matrices• A matrix with only one row is called a row

vector. A row vector can be created in MATLAB as follows (note the commas):

» rowvec = [12 , 14 , 63]

rowvec =

12 14 6385

Page 86: Introduction  to  Simulation language

MATLAB Matrices• A matrix with only one column is called a column

vector. A column vector can be created in MATLAB as follows (note the semicolons):

» colvec = [13 ; 45 ; -2]

colvec =

13 45 -2 86

Page 87: Introduction  to  Simulation language

MATLAB Matrices• A matrix can be created in MATLAB as follows (note the commas AND semicolons):

» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]

matrix =

1 2 3 4 5 6 7 8 9 87

Page 88: Introduction  to  Simulation language

Extracting a Sub-Matrix• A portion of a matrix can be extracted and stored

in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is:

sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;

where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix. 88

Page 89: Introduction  to  Simulation language

MATLAB Matrices A column vector can be

extracted from a matrix. As an example we create a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9]

matrix = 1 2 3 4 5 6 7 8 9

Here we extract column 2 of the matrix and make a column vector:

» col_two=matrix( : , 2)

col_two =

2 5 8

89

Page 90: Introduction  to  Simulation language

MATLAB Matrices

A row vector can be extracted from a matrix. As an example we create a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9]

matrix =

1 2 3 4 5 6 7 8 9

Here we extract row 2 of the matrix and make a row vector. Note that the 2:2 specifies the second row and the 1:3 specifies which columns of the row.

» rowvec=matrix(2 : 2 , 1 : 3)

rowvec =

4 5 690

Page 91: Introduction  to  Simulation language

M-File as script file

91

Save file as filename.m

Type what you want to do, eg. Create matrices

If you include “;” at the end of each statement,result will not be shown immediately

Run the file by typing the filename in the command window

Page 92: Introduction  to  Simulation language

Reading Data from filesMATLAB supports reading an entire file and creating

a matrix of the data with one statement.

>> load mydata.dat; % loads file into matrix.% The matrix may be a scalar, a vector, or a % matrix with multiple rows and columns. The% matrix will be named mydata.>> size (mydata) % size will return the number

% of rows and number of% columns in the matrix

>> length (myvector) % length will return the total% no. of elements in myvector

92

Page 93: Introduction  to  Simulation language

Array, Matrix• a vector x = [1 2 5 1]

x = 1 2 5 1

• a matrix x = [1 2 3; 5 1 4; 3 2 -1]

x = 1 2 3 5 1 4 3 2 -1

• transpose y = x’ y =

12

51

Page 94: Introduction  to  Simulation language

Long Array, Matrix • t =1:10

t = 1 2 3 4 5 6 7 8 9 10

• k =2:-0.5:-1

k = 2 1.5 1 0.5 0 -0.5 -1

• B = [1:4; 5:8]

x = 1 2 3 4 5 6 7 8

Page 95: Introduction  to  Simulation language

Generating Vectors from functions• zeros(M,N) MxN matrix of zeros

• ones(M,N) MxN matrix of ones

• rand(M,N) MxN matrix of uniformly distributed random

numbers on (0,1)

x = zeros(1,3)

x =

0 0 0

x = ones(1,3)

x =

1 1 1

x = rand(1,3)

x =

0.9501 0.2311 0.6068

Page 96: Introduction  to  Simulation language

Matrix Index• The matrix indices begin from 1 (not 0 (as in C)) • The matrix indices must be positive integer

Given:

A(-2), A(0)

Error: ??? Subscript indices must either be real positive integers or logicals.

A(4,2)Error: ??? Index exceeds matrix dimensions.

Page 97: Introduction  to  Simulation language

Concatenation of Matrices• x = [1 2], y = [4 5], z=[ 0 0]

A = [ x y]

1 2 4 5

B = [x ; y]

1 2

4 5

C = [x y ;z] Error:??? Error using ==> vertcat CAT arguments dimensions are not consistent.

Page 98: Introduction  to  Simulation language

Operators (arithmetic)+addition- subtraction* multiplication/ division^power‘ complex conjugate transpose

Page 99: Introduction  to  Simulation language

Matrices Operations

Given A and B:

Addition Subtraction Product Transpose

Page 100: Introduction  to  Simulation language

Operators (Element by Element)

.*element-by-element multiplication

./ element-by-element division

.^ element-by-element power

Page 101: Introduction  to  Simulation language

The use of “.” – “Element” Operation

K= x^2Erorr: ??? Error using ==> mpower Matrix must be square.B=x*yErorr:??? Error using ==> mtimes Inner matrix dimensions must agree.

A = [1 2 3; 5 1 4; 3 2 1] A = 1 2 3 5 1 4 3 2 -1

y = A(3 ,:)

y= 3 4 -1

b = x .* y

b= 3 8 -3

c = x . / y

c= 0.33 0.5 -3

d = x .^2

d= 1 4 9

x = A(1,:)

x= 1 2 3

Page 102: Introduction  to  Simulation language

MATLAB Special Variablesans Default variable name for resultspi Value of

eps Smallest incremental numberinf InfinityNaN Not a number e.g. 0/0i and j i = j = square root of -1realmin The smallest usable positive real numberrealmax The largest usable positive real number 10

2

Page 103: Introduction  to  Simulation language

Plot

PLOT Linear plot. • PLOT(X,Y) plots vector Y

versus vector X• PLOT(Y) plots the columns

of Y versus their index• PLOT(X,Y,S) with plot

symbols and colors • See also SEMILOGX,

SEMILOGY, TITLE, XLABEL, YLABEL, AXIS, AXES, HOLD, COLORDEF, LEGEND, SUBPLOT...

103

x = [-3 -2 -1 0 1 2 3];y1 = (x.^2) -1;plot(x, y1,'bo-.');

Example

Page 104: Introduction  to  Simulation language

Plot Properties

XLABEL X-axis label.

• XLABEL('text') adds text beside the X-axis on the current axis.

YLABEL Y-axis label.

• YLABEL('text') adds text beside the Y-axis on the current axis.

104

...xlabel('x values');ylabel('y values');

Example

Page 105: Introduction  to  Simulation language

Hold

HOLD Hold current graph.

• HOLD ON holds the current plot and all axis properties so that subsequent graphing commands add to the existing graph.

• HOLD OFF returns to the default mode

• HOLD, by itself, toggles the hold state.

105

...hold on;y2 = x + 2;plot(x, y2, 'g+:');

Example

Page 106: Introduction  to  Simulation language

Subplot

SUBPLOT Create axes in tiled positions.

• SUBPLOT(m,n,p), or SUBPLOT(mnp), breaks the Figure window into an m-by-n matrix of small axes

106

x = [-3 -2 -1 0 1 2 3];y1 = (x.^2) -1;% Plot y1 on the topsubplot(2,1,1);plot(x, y1,'bo-.');xlabel('x values');ylabel('y values');% Plot y2 on the bottomsubplot(2,1,2);y2 = x + 2;plot(x, y2, 'g+:');

Example

Page 107: Introduction  to  Simulation language

Figure

FIGURE Create figure window.

• FIGURE, by itself, creates a new figure window, and returns its handle.

107

x = [-3 -2 -1 0 1 2 3];y1 = (x.^2) -1;% Plot y1 in the 1st Figureplot(x, y1,'bo-.');xlabel('x values');ylabel('y values');% Plot y2 in the 2nd Figurefigurey2 = x + 2;plot(x, y2, 'g+:');

Example

Page 108: Introduction  to  Simulation language

Surface Plot

108

x = 0:0.1:2;y = 0:0.1:2;[xx, yy] = meshgrid(x,y);zz=sin(xx.^2+yy.^2);surf(xx,yy,zz)xlabel('X axes')ylabel('Y axes')

Page 109: Introduction  to  Simulation language

109

contourf-colorbar-plot3-waterfall-contour3-mesh-surf

3 D Surface Plot

Page 110: Introduction  to  Simulation language

Basic Task: Plot the function sin(x) between

0≤x≤4π • Create an x-array of 100 samples between 0 and 4π.

• Calculate sin(.) of the x-array

• Plot the y-array

>>x=linspace(0,4*pi,100);

>>y=sin(x);

>>plot(y)0 10 20 30 40 50 60 70 80 90 100

-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

Page 111: Introduction  to  Simulation language

Plot the function e-x/3sin(x) between 0≤x≤4π • Create an x-array of 100 samples between 0 and

4π.

• Calculate sin(.) of the x-array

• Calculate e-x/3 of the x-array

• Multiply the arrays y and y1

>>x=linspace(0,4*pi,100);

>>y=sin(x);

>>y1=exp(-x/3);

>>y2=y*y1;

Page 112: Introduction  to  Simulation language

Plot the function e-x/3sin(x) between 0≤x≤4π

• Multiply the arrays y and y1 correctly

• Plot the y2-array

>>y2=y.*y1;

>>plot(y2)

0 10 20 30 40 50 60 70 80 90 100-0.3

-0.2

-0.1

0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

Page 113: Introduction  to  Simulation language

Display Facilities• plot(.)

• stem(.)

Example:>>x=linspace(0,4*pi,100);>>y=sin(x);>>plot(y)>>plot(x,y)

Example:>>stem(y)>>stem(x,y)

0 10 20 30 40 50 60 70 80 90 100-0.3

-0.2

-0.1

0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0 10 20 30 40 50 60 70 80 90 100-0.3

-0.2

-0.1

0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

Page 114: Introduction  to  Simulation language

Display Facilities• title(.)

• xlabel(.)

• ylabel(.)

>>title(‘This is the sinus function’)

>>xlabel(‘x (secs)’)

>>ylabel(‘sin(x)’)0 10 20 30 40 50 60 70 80 90 100

-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1This is the sinus function

x (secs)

sin(

x)

Page 115: Introduction  to  Simulation language

Line Plots in Two Dimensions

• Plot (x,y)• makes a two-dimensional line plot for each point in X and its

corresponding point in Y: (X(1),Y(1)), (X(2),Y(2)), (X(3),Y(3)), etc., and then connect all these points together with line.

• Example:• >> x=1:1:5;• >>Y=[2 7 0 -8 6];• >> plot (x,y);• >> xlabel (‘label for x-axis’)• >> ylabel (‘label for y-axis’)• >> title (‘title’)

Page 116: Introduction  to  Simulation language

Multiple Plots • Check the following:• x_points = [-10 : .05 : 10];• plot(x_points, exp(x_points)); % plot in Blue (default)• grid on• hold on• plot(x_points, exp(.95 .* x_points), 'm'); % plot in Magenta• plot(x_points, exp(.85 .* x_points), 'g'); % plot in Green• plot(x_points, exp(.75 .* x_points), 'p'); % plot a star• hold off• xlabel('x-axis'); ylabel('y-axis');• title('Comparing Exponential Functions'); • legend ('1', '2', '3', '4')

-10 -5 0 5 100

0.5

1

1.5

2

2.5x 10

4

x-axis

y-ax

is

Comparing Exponential Functions

1234

Page 117: Introduction  to  Simulation language

Subplots• multiple plots in the same window, each with

their own axes.• Subplot (M,N,P) • M – rows• N - columns• P – number of subplot

in the figureSubplot (2,2,1)

Page 118: Introduction  to  Simulation language

Graphics - 2D Plots

plot(xdata, ydata, ‘marker_style’);

For example: Gives:>> x=-5:0.1:5;>> sqr=x.^2;>> pl1=plot(x, sqr, 'r:s');

Page 119: Introduction  to  Simulation language

Graphics - Overlay Plots

Use hold on for overlaying graphsSo the following: Gives:

>> hold on;>> cub=x.^3;>> pl2=plot(x, cub,‘b-o');

Page 120: Introduction  to  Simulation language

Graphics - Annotation

Use title, xlabel, ylabel and legend for annotation

>> title('Demo plot');

>> xlabel('X Axis');

>> ylabel('Y Axis');

>> legend([pl1, pl2], 'x^2', 'x^3');

Page 121: Introduction  to  Simulation language

Graphics - Annotation

Page 122: Introduction  to  Simulation language

Graphics-Stem()

• stem()is to plot discrete sequence data• The usage of stem() is very similar to plot()

>> n=-10:10;>> f=stem(n,cos(n*pi/4))>> title('cos(n\pi/4)')>> xlabel('n')

-10 -5 0 5 10-1

-0.5

0

0.5

1cos(n/4)

n

Page 123: Introduction  to  Simulation language

>> f=figure;>> x=-5:0.1:5;>> h=plot(x,cos(2*x+pi/3));>> title('Figure 1');>> xlabel('x');>> saveas(h,'figure1.fig')>> saveas(h,'figure1.eps')

Save plots

• Use saveas(h,'filename.ext') to save a figure to a file. Useful extension types:

bmp: Windows bitmap emf: Enhanced metafile eps: EPS Level 1 fig: MATLAB figure jpg: JPEG image m: MATLAB M-file tif: TIFF image, compressed

Page 124: Introduction  to  Simulation language

Workspace

• Matlab remembers old commands• And variables as well• Each Function maintains its own scope• The keyword clear removes all

variables from workspace• The keyword who lists the variables

Page 125: Introduction  to  Simulation language

File I/O• Matlab has a native file format to save and

load workspaces. Use keywords load and save.

• In addition MATLAB knows a large number of popular formats. Type “help fileformats” for a listing.

• In addition MATLAB supports ‘C’ style low level file I/O. Type “help fprintf” for more information.

Page 126: Introduction  to  Simulation language

Practice Problems• Plot the following signals in linear scale

• Plot the following signals, use log scale for y-axis

• Plot the real part and imaginary part of the following signal

• For the signal in previous question, plot its phase and magnitude

50)(

55)3sin()(32

tety

tttxt

100)12()( 2 ttetx t

100)( )3/(5.0 tetx tjt

Page 127: Introduction  to  Simulation language

More about figures

• Figure % Open a new figure without closing old figures

• Figure (i) % Open the i-th figure• Close all % close all open figures• axis ([xmin xmax ymin ymax]) % sets

scaling for the x- and y-axes on the current plot.

Page 128: Introduction  to  Simulation language

Exercise

• x = (1, 1.05, 1.1, 1.15… 5)• Y=sin(x)• Z=log(x)• Put your name in the title• Hint: check the doc on function “LineSpec”.

Create the following:

1 1.5 2 2.5 3 3.5 4 4.5 5-1

-0.5

0

0.5

1

1.5

2Merav's graph

x

y

sin(x)log(x)

Page 129: Introduction  to  Simulation language

Solution• x=1:0.05:5;• y=sin(x);• z=log(x);• hold on• plot (x,y,'-.r*')• plot (x,z,'-.go')• hold off• title ('Merav''s graph');• xlabel ('x')• ylabel ('y')• legend ('sin(x)', 'log(x)');

Page 130: Introduction  to  Simulation language

More exercise• Make a 3 three-dimensional graph of (x,y,z) – use

Matlab help.• Make two separate 2-D graphs, with separate axis, in

the same window: y vs. x, and z vs. x.• Use the same x,y,z as defined in the previous exercise

12

34

5

-1

-0.5

0

0.5

10

0.5

1

1.5

2

x

3D graph

y

z

1 2 3 4 5-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1sin(x)

x

y=si

n(x)

1 2 3 4 50

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

x

log(x)

z

Page 131: Introduction  to  Simulation language

Solution• 3-D graph:• >> plot3(x,y,z)• >> grid• >> xlabel ('x')• >> ylabel('y')• >> zlabel('z')• >> title ('3D

graph')

• Subplots>> subplot (1,2,1);>> plot(x,y);>> title ('sin(x)');>> xlabel('x');>> ylabel('y=sin(x)');>> grid;>> subplot (1,2,2);>> plot(x,z);>> xlabel('x');>> title ('log(x)');>> grid;>> ylabel ('z');

Page 132: Introduction  to  Simulation language

Operators (relational, logical)• == Equal to

• ~= Not equal to• < Strictly smaller• > Strictly greater• <= Smaller than or equal to• >= Greater than equal to• & And operator• | Or operator• ~ not % highest precedence

Page 133: Introduction  to  Simulation language

Creating Matrices

• Matrices must be rectangular.• Creating random matrices:

2-by-4 random matrix

(2 rows and 4 columns).

Page 134: Introduction  to  Simulation language

Creating Matrices • You can combine existing vectors as matrix elements:

• You can combine existing matrices as matrix elements:

Page 135: Introduction  to  Simulation language

135

Subarrays• The end function: When used in an array subscript, it returns

the highest value taken on by that subscript. arr3 = [1 2 3 4 5 6 7 8];arr3(5:end) is the array [5 6 7 8]arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];arr4(2:end, 2:end)

• Using subarrays on the left hand-side of an assignment statement:

arr4(1:2, [1 4]) = [20 21; 22 23];(1,1) (1,4) (2,1) and (2,4) are updated.arr4 = [20 21; 22 23]; all of the array is changed.

MATLAB BASICS

Page 136: Introduction  to  Simulation language

Indexing Into a Matrix

>> B=A(3,1);

>> A(:,end)=[1;7;3;8;4];• The row number is first, followed by the column number.

Page 137: Introduction  to  Simulation language

Linear Algebra Operations

Page 138: Introduction  to  Simulation language

Vector MultiplicationType the following:>>a=[2 3]>>b=[3 2]>>a*b

>>a.*b

>>a.*b’

Page 139: Introduction  to  Simulation language

String Arrays

• Created using single quote delimiter (')

• Indexing is the same as for numeric arrays

Page 140: Introduction  to  Simulation language

String Array Concatenation

Page 141: Introduction  to  Simulation language

Working with String Arrays

Page 142: Introduction  to  Simulation language

Example: Solving Equations

• Solve this set of simultaneous equations: Ax=B, x=?

Page 143: Introduction  to  Simulation language

Vectors and Matrices

• How do we assign a value to a variable?

>>> v1=3

v1 =

3

>>> i1=4

i1 =

4

>>> R=v1/i1

R =

0.7500

>>>

>>> whos

Name Size Bytes Class

R 1x1 8 double array

i1 1x1 8 double array

v1 1x1 8 double array

Grand total is 3 elements using 24 bytes

>>> who

Your variables are:

R i1 v1

>>>

Page 144: Introduction  to  Simulation language

Vectors and Matrices

• How do we assign values to vectors?

If we want to construct a vector of, say, 100 elements between 0 and 2 – linspace >>> c1 = linspace(0,(2*pi),100);>>> whos Name Size Bytes Class c1 1x100 800 double arrayGrand total is 100 elements using 800 bytes>>>

Page 145: Introduction  to  Simulation language

Vectors and Matrices

• How do we assign values to vectors?

If we want to construct an array of, say, 100 elements between 0 and 2 – colon notation >>> c2 = (0:0.0201:2)*pi;>>> whos Name Size Bytes Class c1 1x100 800 double array c2 1x100 800 double arrayGrand total is 200 elements using 1600 bytes>>>

Page 146: Introduction  to  Simulation language

Vectors and Matrices

• Some special variables

beep

pi ()

inf (e.g. 1/0)

i, j ( )1

>>> 1/0Warning: Divide by zero.ans = Inf>>> pians = 3.1416>>> ians = 0+ 1.0000i

Page 147: Introduction  to  Simulation language

Vectors and Matrices

• Arithmetic operations – Matrices

Performing operations between matrices

A/B

A./B

0000.36667.23333.20000.35000.20000.20000.30000.20000.1

=

? (matrices singular)

3/93/83/72/62/52/41/31/21/1

Page 148: Introduction  to  Simulation language

Vectors and Matrices

• Arithmetic operations – Matrices

Performing operations between matrices

A^B

A.^B

729512343362516321

=

??? Error using ==> ^At least one operand must be scalar

333

222

111

987654321

Page 149: Introduction  to  Simulation language

149

Changing the data format>> value = 12.345678901234567;

format short 12.3457format long 12.34567890123457format short e 1.2346e+001format long e 1.234567890123457e+001format short g 12.346format long g 12.3456789012346format rat 1000/81

MATLAB BASICS

Page 150: Introduction  to  Simulation language

150

MATLAB BASICSThe disp( array ) function

>> disp( 'Hello' )Hello>> disp(5) 5>> disp( [ 'Bilkent ' 'University' ] )Bilkent University>> name = 'Alper';>> disp( [ 'Hello ' name ] )Hello Alper

Page 151: Introduction  to  Simulation language

151

MATLAB BASICSThe num2str() and int2str() functions

>> d = [ num2str(16) '-Feb-' num2str(2004) ];>> disp(d)16-Feb-2004>> x = 23.11;>> disp( [ 'answer = ' num2str(x) ] )answer = 23.11>> disp( [ 'answer = ' int2str(x) ] )answer = 23

Page 152: Introduction  to  Simulation language

CS 111 152

MATLAB BASICS

The fprintf( format, data ) function– %d integer– %f floating point format– %e exponential format– %g either floating point or exponential

format, whichever is shorter– \n new line character– \t tab character

Page 153: Introduction  to  Simulation language

153

MATLAB BASICS

>> fprintf( 'Result is %d', 3 )Result is 3>> fprintf( 'Area of a circle with radius %d is %f', 3, pi*3^2 )Area of a circle with radius 3 is 28.274334>> x = 5;>> fprintf( 'x = %3d', x )x = 5>> x = pi;>> fprintf( 'x = %0.2f', x )x = 3.14>> fprintf( 'x = %6.2f', x )x = 3.14>> fprintf( 'x = %d\ny = %d\n', 3, 13 )x = 3y = 13

Page 154: Introduction  to  Simulation language

154

MATLAB BASICSData files• save filename var1 var2 …

>> save myfile.mat x y binary>> save myfile.dat x –ascii ascii

• load filename>> load myfile.mat binary>> load myfile.dat –ascii ascii

Page 155: Introduction  to  Simulation language

155

MATLAB BASICSBuilt-in MATLAB Functions• result = function_name( input );

– abs, sign– log, log10, log2– exp– sqrt– sin, cos, tan– asin, acos, atan– max, min– round, floor, ceil, fix– mod, rem

• help elfun help for elementary math functions

Page 156: Introduction  to  Simulation language

156

MATLAB BASICSTypes of errors in MATLAB programs• Syntax errors

– Check spelling and punctuation• Run-time errors

– Check input data– Can remove “;” or add “disp” statements

• Logical errors– Use shorter statements– Check typos– Check units– Ask your friends, assistants, instructor, …

Page 157: Introduction  to  Simulation language

Vectors and Matrices • Arithmetic operations – Matrices

Example:

Solve for V1 and V2

10j10

-j5

1.50o2-90o

Page 158: Introduction  to  Simulation language

Example (cont)

(0.1 + j0.2)V1 – j0.2V2 = -j2

- j0.2V1 + j0.1V2 = 1.5

Vectors and Matrices

• Arithmetic operations – Matrices

1.0j2.0j2.0j2.0j1.0

2

1

VV

=

5.12j

A x y=

Page 159: Introduction  to  Simulation language

Example (cont)

Vectors and Matrices

• Arithmetic operations – Matrices

>>> A=[(0.1+0.2j) -0.2j;-0.2j 0.1j]A = 0.1000+ 0.2000i 0- 0.2000i 0- 0.2000i 0+ 0.1000i>>> y=[-2j;1.5]y = 0- 2.0000i 1.5000>>> x=A\yx = 14.0000+ 8.0000i 28.0000+ 1.0000i>>>

* A\B is the matrix division of A into B, which is roughly the same as INV(A)*B *

Page 160: Introduction  to  Simulation language

Example (cont)

Vectors and Matrices

• Arithmetic operations – Matrices

>>> V1= abs(x(1,:))V1 = 16.1245

>>> V1ang= angle(x(1,:))V1ang = 0.5191

V1 = 16.1229.7o V

Page 161: Introduction  to  Simulation language

Built in functions (commands)

Scalar functions – used for scalars and operate element-wise when applied to a matrix or vector

e.g. sin cos tan atan asin log

abs angle sqrt round floor

At any time you can use the command help to get help

e.g. >>>help sin

Page 162: Introduction  to  Simulation language

Built in functions (commands)

>>> a=linspace(0,(2*pi),10)a = Columns 1 through 7 0 0.6981 1.3963 2.0944 2.7925 3.4907 4.1888 Columns 8 through 10 4.8869 5.5851 6.2832>>> b=sin(a)b = Columns 1 through 7 0 0.6428 0.9848 0.8660 0.3420 -0.3420 -0.8660 Columns 8 through 10 -0.9848 -0.6428 0.0000>>>

Page 163: Introduction  to  Simulation language

Built in functions (commands)Vector functions – operate on vectors returning scalar value

e.g. max min mean prod sum length>>> max(b)ans = 0.9848>>> max(a)ans = 6.2832>>> length(a)ans = 10>>>

>>> a=linspace(0,(2*pi),10);>>> b=sin(a);

Page 164: Introduction  to  Simulation language

Built in functions (commands)Matrix functions – perform operations on matrices

>>> help elmat

>>> help matfun

e.g. eye size inv det eig

At any time you can use the command help to get help

Page 165: Introduction  to  Simulation language

Built in functions (commands)Matrix functions – perform operations on matrices

>>> x=rand(4,4)

x =

0.9501 0.8913 0.8214 0.9218

0.2311 0.7621 0.4447 0.7382

0.6068 0.4565 0.6154 0.1763

0.4860 0.0185 0.7919 0.4057

>>> xinv=inv(x)

xinv =

2.2631 -2.3495 -0.4696 -0.6631

-0.7620 1.2122 1.7041 -1.2146

-2.0408 1.4228 1.5538 1.3730

1.3075 -0.0183 -2.5483 0.6344

>>> x*xinv

ans =

1.0000 0.0000 0.0000 0.0000

0 1.0000 0 0.0000

0.0000 0 1.0000 0.0000

0 0 0.0000 1.0000

>>>

Page 166: Introduction  to  Simulation language

Built in functions (commands)From our previous example,

1.0j2.0j2.0j2.0j1.0

2

1

VV

=

5.12j

A x y=

>>> x=inv(A)*yx = 14.0000+ 8.0000i 28.0000+ 1.0000i

Page 167: Introduction  to  Simulation language

Built in functions (commands)

Data visualisation – plotting graphs

>>> help graph2d

>>> help graph3d

e.g. plot polar loglog mesh

semilog plotyy surf

Page 168: Introduction  to  Simulation language

Built in functions (commands)Data visualisation – plotting graphs

Example on plot – 2 dimensional plotExample on plot – 2 dimensional plot

>>> x=linspace(0,(2*pi),100);>>> y1=sin(x);>>> y2=cos(x);>>> plot(x,y1,'r-')>>> holdCurrent plot held>>> plot(x,y2,'g--')>>>

Add title, labels and legend

title xlabel ylabel legend

Use ‘copy’ and ‘paste’ to add to your window–based document, e.g. MSword

Page 169: Introduction  to  Simulation language

Built in functions (commands)Data visualisation – plotting graphs

0 1 2 3 4 5 6 7-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

angular frequency (rad/s)

y1 a

nd y

2

Example on plot

sin(x)cos(x)

Example on plot – 2 dimensional plot

Page 170: Introduction  to  Simulation language

Built in functions (commands)Data visualisation – plotting graphs

Example on mesh and surf – 3 dimensional plot

>>> [t,a] = meshgrid(0.1:.01:2, 0.1:0.5:7);

>>> f=2;

>>> Z = 10.*exp(-a.*0.4).*sin(2*pi.*t.*f);

>>> surf(Z);

>>> figure(2);

>>> mesh(Z);

Supposed we want to visualize a function

Z = 10e(–0.4a) sin (2ft) for f = 2

when a and t are varied from 0.1 to 7 and 0.1 to 2, respectively

Page 171: Introduction  to  Simulation language

Built in functions (commands)Data visualisation – plotting graphsExample on mesh and surf – 3 dimensional plot

Page 172: Introduction  to  Simulation language

Built in functions (commands)

Data visualisation – plotting graphs

Example on mesh and surf – 3 dimensional plot

>>> [x,y] = meshgrid(-3:.1:3,-3:.1:3);>>> z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...- 1/3*exp(-(x+1).^2 - y.^2);>>> surf(z);

Page 173: Introduction  to  Simulation language

Built in functions (commands)Data visualisation – plotting graphsExample on mesh and surf – 3 dimensional plot

Page 174: Introduction  to  Simulation language

Solution : use M-files

M-files : Script and function files

When problems become complicated and require re–evaluation, entering command at MATLAB prompt is not practical

Collections of commands

Executed in sequence when calledSaved with extension “.m”

Script FunctionUser defined commands

Normally has input & outputSaved with extension “.m”

Page 175: Introduction  to  Simulation language

M-files : script and function files (script)

At Matlab prompt type in edit to invoke M-file editor

Save this file as test1.m

Page 176: Introduction  to  Simulation language

M-files : script and function files (script)

To run the M-file, type in the name of the file at the prompt e.g. >>> test1

Type in matlabpath to check the list of directories listed in the path

Use path editor to add the path: File Set path …

It will be executed provided that the saved file is in the known path

Page 177: Introduction  to  Simulation language

M-files : script and function files (script)

Example – RLC circuit

Exercise 1:Write an m–file to plot Z, Xc and XLversus frequency for R =10, C = 100 uF, L = 0.01 H.

+

V

R = 10 C

L

Page 178: Introduction  to  Simulation language

M-files : script and function files (script)

LC XX

Total impedance is given by:

Example – RLC circuit

C1

LjRZ

When RZ

LC1

o

Page 179: Introduction  to  Simulation language

M-files : script and function files (script)

0 200 400 600 800 1000 1200 1400 1600 1800 20000

20

40

60

80

100

120

Z XcXl

Example – RLC circuit

Page 180: Introduction  to  Simulation language

M-files : script and function files (script)

For a given values of C and L, plot the following versus the frequency

a) the total impedance ,

b) Xc and XL

c) phase angle of the total impedance

for 100 < < 2000

Example – RLC circuit

+

V

R = 10 C

L

Page 181: Introduction  to  Simulation language

M-files : script and function files (script)

0 200 400 600 800 1000 1200 1400 1600 1800 2000-100

-50

0

50

100Phase

0 200 400 600 800 1000 1200 1400 1600 1800 20000

20

40

60

80

100Magnitude

Mag impXc Xl

Example – RLC circuit

Page 182: Introduction  to  Simulation language

M-files : script and function files (function)

• Function is a ‘black box’ that communicates with workspace through input and output variables.

INPUT OUTPUTFUNCTION– Commands

– Functions

– Intermediate variables

Page 183: Introduction  to  Simulation language

M-files : script and function files (function)Every function must begin with a header:

function output=function_name(inputs)

Output variableMust match the file name

input variable

Page 184: Introduction  to  Simulation language

M-files : script and function files (function)

• Function – a simple examplefunction y=react_C(c,f)

%react_C calculates the reactance of a capacitor.%The inputs are: capacitor value and frequency in hz%The output is 1/(wC) and angular frequency in rad/sy(1)=2*pi*f;w=y(1);y(2)=1/(w*c);

File must be saved to a known path with filename the same as the function name and with an extension ‘.m’

Call function by its name and arguments

help react_C will display comments after the header

Page 185: Introduction  to  Simulation language

M-files : script and function files (function)

• Function – a more realistic example

function x=impedance(r,c,l,w)

%IMPEDANCE calculates Xc,Xl and Z(magnitude) and %Z(angle) of the RLC connected in series%IMPEDANCE(R,C,L,W) returns Xc, Xl and Z (mag) and %Z(angle) at W rad/s%Used as an example for IEEE student, UTM %introductory course on MATLAB

if nargin <4 error('not enough input arguments') end;x(1) = 1/(w*c);x(2) = w*l;Zt = r + (x(2) - x(1))*i; x(3) = abs(Zt);x(4)= angle(Zt);

Page 186: Introduction  to  Simulation language

We can now add our function to a script M-file

R=input('Enter R: ');C=input('Enter C: ');L=input('Enter L: ');w=input('Enter w: ');y=impedance(R,C,L,w);fprintf('\n The magnitude of the impedance at %.1f rad/s is %.3f ohm\n', w,y(3));fprintf('\n The angle of the impedance at %.1f rad/s is %.3f degrees\n\n', w,y(4));

M-files : script and function files (function)

Page 187: Introduction  to  Simulation language

Creating Scripts with MATLAB Editor/Debugger

Automatically saves files as ASCII text files for you.

Scripts in MATLAB has the ".m" suffix. They are also called "M-files".

Open Matlab Editor: File New M-file OR: >> edit

Run

Page 188: Introduction  to  Simulation language

Add path

• >>addpath     C:\EMEM899\Somedirectory

• Set path

Page 189: Introduction  to  Simulation language

Script M-files• Standard ASCII text files• Contain a series of MATLAB expressions• A script does not define a new workspace

% Comments start with "%" character

pause % Suspend execution - hit any key to continue.

keyboard % Pause & return control to command line. % Type "return" to continue.

break % Terminate execution of current loop/file.

return % Exit current function % Return to invoking function/command line.Continue % go to next iterationInput % Prompt for user input

Page 190: Introduction  to  Simulation language

A Simple Script

% a simple MATLAB m-file to calculate the% square root of an input numbers.

my_num=input('insert a number');% now calculate the square root of the number and print it out:

square_root = sqrt(my_num)

Write a program which receives a number from the user, calculates it’s square root (use ‘sqrt’ command) and displays the result.save the script as "square_root_script.m" in your own folder

Page 191: Introduction  to  Simulation language

Running Scripts• >> square_root_script • The header - comments you place at the beginning of your scripts

will be returned to users when they get help for your script.• >> help square_root_script

• Note: The variables defined in the script remain in the workspace even after the script finishes running.

• Creating comments: ctrl+r, or right click on the mouse, or%{comentcoment%}

Page 192: Introduction  to  Simulation language

Flow Control• if • for • while • break • ….

Page 193: Introduction  to  Simulation language

Control Structures • If Statement Syntax

if (Condition_1)Matlab Commands

elseif (Condition_2)Matlab Commands

elseif (Condition_3)Matlab Commands

elseMatlab Commands

end

Some Dummy Examples

if ((a>3) & (b==5)) Some Matlab Commands;End

if (a<3) Some Matlab Commands;elseif (b~=5) Some Matlab Commands;End

if (a<3) Some Matlab Commands;else Some Matlab Commands;end

Page 194: Introduction  to  Simulation language

Control Structures

• For loop syntax

for i=Index_ArrayMatlab Commands

end

Some Dummy Examples

for i=1:100 Some Matlab Commands;end

for j=1:3:200 Some Matlab Commands;end

for m=13:-0.2:-21 Some Matlab Commands;end

for k=[0.1 0.3 -13 12 7 -9.3] Some Matlab Commands;end

Page 195: Introduction  to  Simulation language

Control Structures

• While Loop Syntax

while (condition)Matlab Commands

end

Dummy Example

while ((a>3) & (b==5)) Some Matlab Commands;end

Page 196: Introduction  to  Simulation language

Switch, Case, and Otherwise

switch input_num

case -1

input_str = 'minus one';

case 0

input_str = 'zero';

case 1

input_str = 'plus one';

case {-10,10}

input_str = '+/- ten';

otherwise

input_str = 'other value';

end

• More efficient than elseif statements

• Only the first matching case is executed

Page 197: Introduction  to  Simulation language

Problem

• Build a program which receives a variable x and its units(mm, cm, inch, meter) and calculates Y- it’s value in centimeters units.

• Use switch case.• 1 Inch = 2.54 cm• Write a comment for error case.• Save the file under units.m

Page 198: Introduction  to  Simulation language

Solutionx = 3.0; units = 'mm'; switch units case {'in','inch'}

y = 2.54*x       % converts to centimeterscase {'m','meter'}

y = x*100       % converts to centimeters case { 'millimeter','mm'}

y = x/10; disp    ([num2str(x)  '   in   ' units ' converted to cm is :' num2str(y)])

case {'cm','centimeter'} y = x

otherwise  disp    (['unknown units:' units])     y = nan;

end

Page 199: Introduction  to  Simulation language

Use of M-FileClick to create a new M-File

• Extension “.m” • A text file containing script or function or program to run

Page 200: Introduction  to  Simulation language

Use of M-File

If you include “;” at the end of each statement,result will not be shown immediately

Save file as Denem430.m

Page 201: Introduction  to  Simulation language

Writing User Defined Functions • Functions are m-files which can be executed by

specifying some inputs and supply some desired outputs.

• The code telling the Matlab that an m-file is actually a function is

• You should write this command at the beginning of the m-file and you should save the m-file with a file name same as the function name

function out1=functionname(in1)function out1=functionname(in1,in2,in3)function [out1,out2]=functionname(in1,in2)

Page 202: Introduction  to  Simulation language

Writing User Defined Functions • Examples

• Write a function : out=squarer (A, ind)• Which takes the square of the input matrix if the

input indicator is equal to 1• And takes the element by element square of the

input matrix if the input indicator is equal to 2

Same Name

Page 203: Introduction  to  Simulation language

Writing User Defined Functions • Another function which takes an input array and returns the sum

and product of its elements as outputs

• The function sumprod(.) can be called from command window or an m-file as

Page 204: Introduction  to  Simulation language

Creating VectorsCreate vector with equally spaced intervals>> x=0:0.5:pix = 0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000

Create vector with n equally spaced intervals>> x=linspace(0, pi, 7)x = 0 0.5236 1.0472 1.5708 2.0944 2.6180 3.1416

Equal spaced intervals in logarithm space>> x=logspace(1,2,7)x = 10.0000 14.6780 21.5443 … 68.1292 100.0000

Note: MATLAB uses pi to represent , uses i or j to represent imaginary unit

Page 205: Introduction  to  Simulation language

Creating Matrices

• zeros(m, n): matrix with all zeros• ones(m, n): matrix with all ones. • eye(m, n): the identity matrix • rand(m, n): uniformly distributed random• randn(m, n): normally distributed random• magic(m): square matrix whose elements have

the same sum, along the row, column and diagonal.

• pascal(m) : Pascal matrix.

Page 206: Introduction  to  Simulation language

Variables

• Don’t name your variables the same as functions

• min, max, sqrt, cos, sin, tan, mean, median, etc

• Funny things happen when you do this

• MATLAB reserved words don’t work either

• i, j, eps, nargin, end, pi, date, etc• i, j are reserved as complex numbers initially

• Will work as counters in my experience so they can be redefined as real numbers

Page 207: Introduction  to  Simulation language

Notes:• “%” is the neglect sign for Matlab (equaivalent of “//” in C). Anything after it on the same line is neglected by Matlab compiler.

• Sometimes slowing down the execution is done deliberately for observation purposes. You can use the command “pause” for this purpose

pause %wait until any keypause(3) %wait 3 seconds

Page 208: Introduction  to  Simulation language

MATLAB Toolboxes• MATLAB has a number of add-on software modules, called

toolbox , that perform more specialized computations.

• Signal Processing• Image Processing • Communications• System Identification• Wavelet  Filter Design    • Control System • Fuzzy Logic • Robust Control• µ-Analysis and Synthesis • LMI Control • Model Predictive Control• …

208

208

Page 209: Introduction  to  Simulation language

MATLAB Help• Ways to get help in MATLAB• help function name• Provides basic text

output

• Type helpwin on command line

• Look under the help menu on the desktop

Page 210: Introduction  to  Simulation language

MATLAB Help• Product help window

• Help>product help

Page 211: Introduction  to  Simulation language

Useful Commands• The two commands used most by Matlab

users are

>>help functionname

>>lookfor keyword

Page 212: Introduction  to  Simulation language

Resources

• Books• Two that seem to be good:

• A Concise Introduction to MATLAB by William J. Palm III. 2008, McGraw-Hill, 418 pp.

• Essential MATLAB for Engineers and Scientists (Fourth Edition) by Brian Hahn and Dan Valentine. 2010, Academic Press, 480 pp.

• Online tutorials and examples are everywhere• Note that older books and tutorials may have

options that are no longer available and functions that no longer work

• Figures are the prime example

Page 213: Introduction  to  Simulation language

Simulink

Used to model, analyze and simulate dynamic systems using block diagrams.

Provides a graphical user interface for constructing block diagram of a system – therefore is easy to use. However modeling a system is not necessarily easy !

Page 214: Introduction  to  Simulation language

Simulink

Model – simplified representation of a system – e.g. using mathematical equation

We simulate a model to study the behavior of a system – need to verify that our model is correct – expect results

Knowing how to use Simulink or MATLAB does not mean that you know how to model a system

Page 215: Introduction  to  Simulation language

• Two main sets of libraries for building simple simulations in Simulink:

• Signals: Sources and Sinks• Systems: Continuous and Discrete

215/14

Page 216: Introduction  to  Simulation language

Basic Simulink Example• Copy “sine wave” source and “scope” sink

onto a new Simulink work space and connect.

• Set sine wave parameters modify to 2 rad/sec

• Run the simulation:• Simulation - Start

• Open the scope and leave open while you change parameters (sin or simulation parameters) and re-run

• Many other Simulink demos …

Page 217: Introduction  to  Simulation language

Example 1: a simple model• Build a Simulink model that solves the

differential equation

• Initial condition• First, sketch a simulation diagram of this

mathematical model (equation)(3 min.)

tx 2sin3.1)0( x

Page 218: Introduction  to  Simulation language

Simulation diagram• Input is the forcing function 3sin(2t)• Output is the solution of the differential

equation x(t)

• Now build this model in Simulink

xxs1

3sin(2t)(input)

x(t)(output)

1)0( x

integrator

Page 219: Introduction  to  Simulation language

Select an input blockDrag a Sine Wave block from the Sources library to the model window

Page 220: Introduction  to  Simulation language

Select an operator blockDrag an Integrator block from the Continuous library to the model window

Page 221: Introduction  to  Simulation language

Select an output blockDrag a Scope block from the Sinks library to the model window

Page 222: Introduction  to  Simulation language

Connect blocks with signals

• Place your cursor on the output port (>) of the Sine Wave block

• Drag from the Sine Wave output to the Integrator input

• Drag from the Integrator output to the Scope input

Arrows indicate the direction of the signal flow.

Page 223: Introduction  to  Simulation language

Select simulation parameters

Double-click on the Sine Wave block to set amplitude = 3 and freq = 2.

This produces the desired input of 3sin(2t)

Page 224: Introduction  to  Simulation language

Select simulation parameters

Double-click on the Integrator block to set initial condition = -1.

This sets our IC x(0) = -1.

Page 225: Introduction  to  Simulation language

Select simulation parameters

Double-click on the Scope to view the simulation results

Page 226: Introduction  to  Simulation language

Run the simulationIn the model window, from the Simulation pull-down menu, select Start

View the output x(t) in the Scope window.

Page 227: Introduction  to  Simulation language

Simulation resultsTo verify that this plot represents the solution to the problem, solve the equation analytically.

The analytical result,

matches the plot (the simulation result) exactly.

ttx 2cos)( 23

21

Page 228: Introduction  to  Simulation language

Example 2• Build a Simulink model that solves the

following differential equation• 2nd-order mass-spring-damper system• zero ICs• input f(t) is a step with magnitude 3• parameters: m = 0.25, c = 0.5, k = 1

)(tfkxxcxm

Page 229: Introduction  to  Simulation language

Create the simulation diagram

• On the following slides:• The simulation diagram for solving the ODE

is created step by step.• After each step, elements are added to the

Simulink model.

• Optional exercise: first, sketch the complete diagram (5 min.)

)(tfkxxcxm

Page 230: Introduction  to  Simulation language

(continue)• First, solve for the term with highest-order

derivative

• Make the left-hand side of this equation the output of a summing block

kxxctfxm )(

xm

summing block

Page 231: Introduction  to  Simulation language

Drag a Sum block from the Math library

Double-click to change the block parameters to rectangular and + - -

Page 232: Introduction  to  Simulation language

(continue)• Add a gain (multiplier) block to eliminate the

coefficient and produce the highest-derivative alone

xm m1 x

summing block

Page 233: Introduction  to  Simulation language

Drag a Gain block from the Math library

Double-click to change the block parameters.Add a title.

The gain is 4 since 1/m=4.

Page 234: Introduction  to  Simulation language

(continue)• Add integrators to obtain the desired output

variable

xm m1

summing block

s1

s1x xx

Page 235: Introduction  to  Simulation language

Drag Integrator blocks from the Continuous library

Add a scope from the Sinks library.Connect output ports to input ports.Label the signals by double-clicking on the leader line.

ICs on the integrators are zero.

Page 236: Introduction  to  Simulation language

(continue)• Connect to the integrated signals with

gain blocks to create the terms on the right-hand side of the EOM

xm m1

summing block

s1

s1x x x

c

k

xc

kx

Page 237: Introduction  to  Simulation language

Drag new Gain blocks from the Math library

Double-click on gain blocks to set parameters

Connect from the gain block input backwards up to the branch point.

Re-title the gain blocks.

To flip the gain block, select it and choose Flip Block in the Format pull-down menu.

c=0.5

k=1.0

Page 238: Introduction  to  Simulation language

Complete the model• Bring all the signals and inputs to the

summing block.• Check signs on the summer.

xm m1

s1

s1x x

c

k

xc

kx

f(t)input

+-

-x

x

x x(t)output

Page 239: Introduction  to  Simulation language

Double-click on Step block to set parameters. For a step input of magnitude 3, set Final value to 3

Page 240: Introduction  to  Simulation language

Final Simulink model

Page 241: Introduction  to  Simulation language

Run the simulation

Page 242: Introduction  to  Simulation language

Results

Underdamped response.Overshoot of 0.5.Final value of 3.Is this expected?

Page 243: Introduction  to  Simulation language

SimulinkProblem: We need to simulate the resonant circuit and display the current waveform as we change the frequency dynamically.

+

v(t) = 5 sin t

i 10 100 uF

0.01 HVaries from 0 to 2000 rad/s

Observe the current. What do we expect ?

The amplitude of the current waveform will become maximum at resonant frequency, i.e. at = 1000 rad/s

Page 244: Introduction  to  Simulation language

Simulink

How to model our resonant circuit ?

+

v(t) = 5 sin t

i 10 100 uF

0.01 H

idtC1

dtdi

LiRv

Writing KVL around the loop,

Page 245: Introduction  to  Simulation language

Simulink

LCi

dtid

LR

dtdi

dtdv

L1

2

2

Differentiate wrt time and re-arrange:

Taking Laplace transform:

LCI

IssILR

LsV 2

LC1

sLR

sIL

sV 2

Page 246: Introduction  to  Simulation language

Simulink

Thus the current can be obtained from the voltage:

LC1

sLR

s

)L/1(sVI

2

LC1

sLR

s

)L/1(s2

V I

Page 247: Introduction  to  Simulation language

Simulink

Start Simulink by typing simulink at Matlab prompt

Simulink library and untitled windows appear

It is here where we construct our model.

It is where we obtain the blocks to construct our model

Page 248: Introduction  to  Simulation language

SimulinkConstructing the model using Simulink:

‘Drag and drop’ block from the Simulink library window to the untitled window

1

s+1Transfer Fcn

simout

To WorkspaceSine Wave

Page 249: Introduction  to  Simulation language

Simulink

Constructing the model using Simulink:

LC1

sLR

s

)L/1(s2 62 101s1000s

)100(s

100s

s +1000s+1e62

Transfer Fcn

v

To Workspace1

i

To WorkspaceSine Wave

Page 250: Introduction  to  Simulation language

We need to vary the frequency and observe the current

100s

s +1000s+1e62

Transfer Fcn1

v

To Workspace3w

To Workspace2i

To Workspace

Ramp

s

1

Integrator

sin

ElementaryMath

Dot Product3Dot Product2

1000

Constant

5

Amplitude

…From initial problem definition, the input is 5sin(ωt).You should be able to decipher why the input works, but you do not need to create your own input subsystems of this form.

Page 251: Introduction  to  Simulation language

Simulink

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-1

-0.5

0

0.5

1

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-5

0

5

Page 252: Introduction  to  Simulation language

The waveform can be displayed using scope – similar to the scope in the lab

100s

s +1000s+1e62

Transfer Fcn

0.802

SliderGain

Scopes

1

Integrator

sin

ElementaryMath

Dot Product2

5

Constant1

2000

Constant

Page 253: Introduction  to  Simulation language

Example: An Electrical Circuit System

• Simulink representation of the electrical circuit

EE-2027 SaS, L1

253/20

+- i

vcvs

RC )(1)(1)(

)()(

)()()(

tvRC

tvRCdt

tdvdt

tdvCti

Rtvtvti

scc

c

cs

vs(t) vc(t)

first ordersystem

v s, v c

t

Page 254: Introduction  to  Simulation language

• Type the following at the Matlab command prompt

• >> simulink• The following Simulink library should appear

254/20

Page 255: Introduction  to  Simulation language

Introduction to Matlab/Simulink

• Click File-New to create a new workspace, and drag and drop objects from the library onto the workspace.

• Selecting Simulation-Start from the pull down menu will run the dynamic simulation. Click on the blocks to view the data or alter the run-time parameters

EE-2027 SaS, L1

255/20

Page 256: Introduction  to  Simulation language

Questions

• ?• ?• ?• ?• ?

Page 257: Introduction  to  Simulation language

Thank You…