0% found this document useful (0 votes)
78 views

ELEC2146 L2 SimProg V03 PDF

This document provides an overview of simulation programming and MATLAB for an electrical engineering modelling and simulation course. It discusses the differences between general programming and simulation programming, programming principles like top-down design and data structures, and how MATLAB works as an interpreted, procedural language that is well-suited for numerical simulations through its use of matrices and built-in functions.

Uploaded by

vince kafua
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

ELEC2146 L2 SimProg V03 PDF

This document provides an overview of simulation programming and MATLAB for an electrical engineering modelling and simulation course. It discusses the differences between general programming and simulation programming, programming principles like top-down design and data structures, and how MATLAB works as an interpreted, procedural language that is well-suited for numerical simulations through its use of matrices and built-in functions.

Uploaded by

vince kafua
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

ELEC2146

Electrical Engineering Modelling and Simulation

Simulation Programming and MATLAB

Dr Julien Epps
S2, 2011

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 1


Overview
 Programming vs. simulation
programming
 Programming principles
 How MATLAB works
 Getting to know MATLAB
 C : A refresher
 Debugging
 Good programming practise

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 2


Simulation Programming
 Most programming:
– Uses a variety of data structures
– Need to declare all variables (‘strongly typed’)
– Often need to worry about memory allocation of
variables
– Visual component = GUI
 Often need libraries to implement this easily
– Few pre-defined functions

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 3


Simulation Programming
 Simulation programming:
– Often uses just numbers, arrays and matrices
 Often not very focused on data structures
– Algorithm-focused
– Visual component = plots (GUI possible)
 Aim is to visualise data easily
– MATLAB
 No need to worry about
– declaring variables
– memory allocation
– Nearly every function is predefined

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 4


Simulation Programming
 Comparing programming languages
C
– Readability
Fair
– Writability OK
– Reliability
 Everything except pointers OK
 Pointers (buffer overflow) Bad
– Cost
 Writing/debugging code Fair
 Execution time Good
– Portability OK
– Generality OK

Adapted from Reus, B. “Principles of Programming Languages” http://www.cogs.susx.ac.uk/users/bernhard/ppl2007/Slides/ppl2s.pdf

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 5


Simulation Programming
 Comparing programming languages
MATLAB
– Readability
OK
– Writability Good
– Reliability
 Everything except memory management Good
 Memory management Bad
– Cost
 Writing/debugging code Good
 Execution time Not great
– Portability Bad
– Generality Bad

Adapted from Reus, B. “Principles of Programming Languages” http://www.cogs.susx.ac.uk/users/bernhard/ppl2007/Slides/ppl2s.pdf

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 6


Programming Principles
 How computers are organised
Central Processing Random Access
Unit Caches Memory
Instruction
Data
I/O Storage Data
Keyboard HDD Data
Mouse DVD Instruction
Ports etc USB etc Instruction . . . .

 Programs are a set of instructions on


data, executed by the CPU
 Data exists in storage (slow), RAM (fast)
or in a CPU cache (fastest)
Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 7
Programming Principles
 Top-down design
– In procedural languages, code development is
based on a step-wise refinement of the abstract
function that the code is required to perform
– Breaks a problem into sub-problems
 And from there into sub-sub-problems
 Deals with each sub-problem separately
– Example:
% Problem: Get to UNSW

CheckTimetable(date,timetable);
DoINeedToGo(date,timetable); CheckSocialSchedule(date);

CheckGearNeeded(date,timetable);
WhatDoINeed(date,timetable); Raining(windowCam);
HotCold(temperature);
DrivingHassle(date,trafficCond);
GetThere(homeGPS,UNSWGPS);
NextBus(date,time);
NextTrain(date,time);

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 8


Programming Principles
 Top-down design
– Start solution to sub-problems by writing pseudo-
code
 Comments containing code-like statements or even just text
descriptions of the function being performed
– Wherever possible, find generic, atomic pieces of the
problem and write them as functions
 Should be as independent and self-contained as possible
 Typically have one entry and one exit point
 Usually short
 Makes code easier to read; improves underlying logic
 Makes code easier to test
 Large projects: can split up work

 MATLAB: can start new file for function or include it as part of a


script file function b = sqrt(a)

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 9


Programming Principles
 Data structures: MATLAB
– Most common type of variable: double
 64-bit double-precision floating-point
 Can hold real, imaginary and complex numbers
– Arrays
 The fundamental data type of MATLAB
 1-D, e.g. array = [1 3 2 4];
 2-D (matrix), e.g. A = [1 3; 2 4];
 3-D and beyond, e.g. B(2,1,4) = 16;
– Characters (not used much in this course)
– Cell arrays (not used much in this course)
 Generic containers – very handy
 ExampleCell{1} = [1 3 2 4]; ExampleCell{2} = 56;
ExampleCell{3} = ‘Hello’;

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 10


Programming Principles
 MATLAB detaches developer from
memory management
– Dynamic variable size
A = 1;
 A is a scalar: double A;
A(2) = 4;
 A is now a 1x2 array: double A[2];
A(3,2) = -1;
 A is now a 3x2 matrix: double A[3][2];
A(3,2,2) = 6;
 A is now 3x2x2: double A[3][2][2];
– Growing an array within a loop
B=0; for k=1:100, B(k)=100-k; end
– “Weakly dynamically typed”
Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 11
How MATLAB works
 High level language
 Huge amount of abstraction from the machine-level instructions
 Programming languages don’t come much higher level than this

 Procedural language
 Complex problems can be decomposed into a hierarchy of
functions

 Interpreted language
– Each line of code is decoded as the compiler
reaches it
 Slower than compiled languages. MATLAB now has a compiler

 Based on fast numerical methods


 LINPACK, EISPACK

 Like an advanced calculator


Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 12
How MATLAB works

Command window
Workspace browser Note that variables defined here
can be seen inside MATLAB
scripts

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 13


How MATLAB works
 Where data is stored in memory

Used during command MATLAB workspace


execution command window
Not accessible to programmer workspace browser

Central Processing Random Access


Unit Caches Memory
Instruction
Data
I/O Storage Data
Keyboard file
HDD load file
Data
Mouse DVD
Ports etc
system
USB etc
Instruction
Instruction . . . .

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 14


How MATLAB works
 Scripts
– A list of commands, stored in exampleScript.m
– Execute by running exampleScript in the
command window
– Think of scripts as identical to the command window
 Functions
– Should always be used in preference to scripts,
where possible to produce generic, reusable code
– Take inputs, produce outputs
– Execute in command window by running e.g.
c = dist(a,b);
function d = dist(x,y)
d = sqrt(sum((x-y).^2));

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 15


How MATLAB works
 Built-in functions
– Lots of them
– Very useful
– Functions are “overloaded”
 Same function can take different inputs or produce different
outputs depending on how it is called
>> x = rand(10,10,10);
>> mean(x)
ans(:,:,1) =
0.6239 0.6602 0.5873 0.3978 0.5614 0.4500
0.5154 0.4969 0.5980 0.3891 etc . . . .
>> x = rand(10,10);
>> mean(x)
ans =
0.4441 0.5751 0.3666 0.6025 0.4448 0.6426
0.3992 0.6124 0.5794 0.4805
>> x = rand(1,10);
>> mean(x)
ans =
0.5878
Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 16
How MATLAB works
 Some MATLAB tips
– If your code is slow, avoid for loops
 Try to use vectors and matrices – MATLAB is fast for these
 Other languages: for loops are fine
– If your code is slow, work out where the problem is
 Use the profiler: help profile
– If your code is slow, reduce your memory usage

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 17


Getting to know MATLAB
 Plots
I = [1 2 3 4 5]; % shorthand: I = 1:5;
R = 4.7;
V = I*R;
plot(I,V);
xlabel(‘Current (A)’); % ALWAYS lable axes
ylabel(‘Voltage (V)’);
title(‘Resistor voltage-current relationship’);

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 18


Getting to know MATLAB
 Plots
Resistor voltage-current relationship
24

22

20

18

16
Voltage (V)

14

12

10

4
1 1.5 2 2.5 3 3.5 4 4.5 5
Current (A)

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 19


Getting to know MATLAB
 Plots
I = 1:0.1:5; % now in increments of 0.1 A
R1 = 4.7;
V1 = I*R1;
R2 = 10;
V2 = I*R2;
subplot(2,1,1); plot(I,V1);
subplot(2,1,2); plot(I,V2);

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 20


Getting to know MATLAB
 Plots
25

20

15
Note:
10
axes
5
have 0
1 1.5 2 2.5 3 3.5 4 4.5 5
different
scaling: 50

difficult to 40

interpret 30

20

10
1 1.5 2 2.5 3 3.5 4 4.5 5

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 21


Getting to know MATLAB
 Plots
I = 1:0.1:5; % now in increments of 0.1 A
R1 = 4.7;
V1 = I*R1;
R2 = 10;
V2 = I*R2;
subplot(2,1,1); plot(I,V1); axis([1 5 0 50]);
ylabel(‘Voltage (V1)’);
title(‘V-I relationship for two resistors’);
subplot(2,1,2); plot(I,V2); axis([1 5 0 50]);
ylabel(‘Voltage (V2)’);
xlabel(‘Current (A)’);

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 22


Getting to know MATLAB
 Plots
V-I relationship for two resistors
50

40
Voltage (V1)

30

20

10

0
1 1.5 2 2.5 3 3.5 4 4.5 5

50

40
Voltage (V2)

30

20

10

0
1 1.5 2 2.5 3 3.5 4 4.5 5
Current (A)
Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 23
Getting to know MATLAB
 Plots
I = 5:-0.1:1; % now in decreasing steps of 0.1 A
R1 = 4.7;
V1 = I*R1;
R2 = 10;
V2 = I*R2;
plot(I,V1,I,V2); % plots on same axes
legend(‘R1’,’R2’);

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 24


Getting to know MATLAB
 Plots
50

45 R1
R2
40

35

30
Voltage (V)

25

20

15

10

0
1 1.5 2 2.5 3 3.5 4 4.5 5
Current (A)
Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 25
Getting to know MATLAB
 Plots
I = 5:-0.1:1; % now in decreasing steps of 0.1 A
R1 = 4.7;
V1 = I*R1;
R2 = 10;
V2 = I*R2;
plot(I,V1);
hold;
plot(I,V2); % plots on same axes (alternative)

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 26


Getting to know MATLAB
 Plots
– See also:

– text – good way to put text where you want it in


the figure
– ginput – returns x-y coordinates of wherever you
click in the axes
– plot(x,y,’r’) – plots in red
– plot(x,y,’:’) – plots dotted line

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 27


Getting to know MATLAB
 Matrix/vector definition
x = [4 7 2 1]; % row vector
x = zeros(1,3);
x = ones(1,7);

x = [4; 7; 2; 1]; % column vector


x = zeros(3,1);
x = ones(7,1);

x = [1 3; 4 6; 7 9]; % 3x2 matrix


x = [ones(1,150); zeros(1,150)]; % 2x150 matrix

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 28


Getting to know MATLAB
 Matrix/vector indexing
x = [4 7 2 1];
x(3) % 3rd element of x (=2)

x = [4; 7; 2; 1];
x(3) % 3rd element of x (=2)

x = [1 3; 4 6; 7 9];
x(2,1) % 2nd row, 1st column (=4)
x(2,:) % all of 2nd row (= [4 6])
x(:,1) % all of 1st column (= [1; 4; 7])

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 29


Getting to know MATLAB
 Matrix/vector manipulation
x = [4 7 2 1];
x’ % matrix/vector transpose
% (= [4; 7; 2; 1])
% careful if x is complex (-> conj.)

A = [1 3; 4 6; 7 9; 2 5];
x*A % matrix multiplication
% dimensions must agree
% (= [48 77])

A’*x’ = [48; 77]

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 30


Getting to know MATLAB
 Matrix/vector manipulation: “.”
x = [4 7 2 1]; y = [1 2 3 4];
x.*y % element by element multiplication
% = [4 14 6 4]
2.^y % element by element “^”
% = [2 4 8 16]
1./y % element by element “1/”
% = [1 0.5 0.33 0.25]
(x.^2+y.^2)./(x-2*y)
% element by element operations
% require careful use of “.”

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 31


Getting to know MATLAB
 Loops
x = [4 7 2 1]; y = [1 2 3 4];
for k = 1:4,
z(k) = (x(k)^2+y(k)^2)/(x(k)-2*y(k));
end

% slower than (x.^2+y.^2)./(x-2*y)

% see also: while

% see also: control flow


% if / then / else, case / switch

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 32


C : A Refresher
 Array (vector) operations
#include math.h
void main {
float x[4] = {4,7,2,1},
y[4] = {1,2,3,4}, z[4];

for (k=0; k<4; k++) {


z[k] = (pow(x[k],2)+pow(y[k],2))
/(x[k]-2*y[k]);
printf(“%f ”,z[k]);
} // can use cout for printf in C++
}
// MATLAB: (x.^2+y.^2)./(x-2*y)
Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 33
C : A Refresher
 Pointers
void main {
int* x;
int* y;

x = malloc(sizeof(int));
// Allocate an int pointee,
// and set x to point to it
// can use “new” (C++) instead

source: http://cslibrary.stanford.edu/106/
Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 34
C : A Refresher
 Pointers
*x = 42; // Dereference x to store
42 in its pointee

*y = 13; // CRASH -- y does not


have a pointee yet

source: http://cslibrary.stanford.edu/106/
Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 35
C : A Refresher
 Pointers
y = x; // Pointer assignment
sets y to point to x's pointee

*y = 13; // Dereference y to store


13 in its (shared) pointee

source: http://cslibrary.stanford.edu/106/
Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 36
C : A Refresher
 Functions
– Don’t forget to
 Declare prototype
 Give types for all arguments and outputs
– e.g.
float dist(float x, float y, int d);
float a[5], b[5]; int k = 5;
void main {
dist(a,b,k);
}
float dist(float x, float y, int d) {
// code implementing ‘dist’ function
}

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 37


Debugging
 Writing code is the easy part
– Figuring out why it doesn’t work is the hard part
Some advice:
 Understand the big objective of
debugging: Systematically isolating the
point of error
– Try to eliminate parts of the code that could not
have produced the error
 Work out what should have happened
where the bug occurred
– Try the code using a simpler input
Adapted from White, A., “Teaching debugging – giving novices expert knowledge”, Artificial Intelligence in
Education, Boulay and Mizoguchi (Eds) , IOS Press, 1997
Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 38
Debugging
 MATLAB will usually locate the problem
line of code
 Try executing the code in the command
window (if using a script or function)
 Try leaving the “;” off the end of the
command
 Prints output to command window

 Check the dimensions of g and r

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 39


MATLAB Debugging Tools
 echo
– Displays every command before it is executed
 size(x)
– Returns the dimensions of array x
 keyboard
– Stops execution, allows input from keyboard
– Afterwards, use return to return to execution
 plot – code runs OK, results wrong
 pause – need to step through code
 Use the debug menu
– Set / clear breakpoints
– Step in and out
– Mainly good practise for similar debuggers in C etc

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 40


Debugging
 Typical problem:
– “I built it and it doesn’t work”
 Understand exactly what “working”
means
 Break “it” up into smaller subsections
 Test each subsection
– With the simplest possible test you can construct
 Better still:
– Do this as you create the code
– Test as you go

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 41


Good programming practise
 Why ?
– Good programming is about communication
– Well-written code is more likely to have fewer errors
– Well-written code is easier to debug
– Well-written code is more extensible and re-usable
– Well-written code is easier for someone else to
understand
 Very important in industry

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 42


Good programming practise
 Code formatting
– A new level of indentation should be used for every
nested statement
for k = 1:N,
if array[k] > threshold,
disp(‘above’);
else
disp(‘below’);
end
end

– MATLAB has “smart indent” – use it

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 43


Good programming practise
 Variables
– Newly declared variables should have a comment
explaining their use
VC = zeros(1,100); % Array of capacitor voltages
– Use meaningful, descriptive variable names
 E.g. VC or CapVolt or CapacitorVoltage for a capacitor voltage
– Don’t change the value of loop variables within a
loop
– Avoid use of global variables
 Easy if you use functions
– Pre-allocate arrays to some fixed length
 Not critical for MATLAB (no need to declare arrays), but faster
and good practise
– Avoid using i, j – MATLAB complex numbers

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 44


Good programming practise
 Function headers
– All useful functions/subroutines/scripts/methods
have headers
– Should give:
 The name of the function
 Its purpose
 Description of all inputs
 Description of all outputs
 Author, date
 Version number (if you create more than one version)
% function C = lbg(data,csize)
%
% LBG algorithm for codebook design
% data : matrix with training vectors in rows
% csize : desired codebook size (must be a power of 2)
% C : codebook with csize rows
%
% Author: Julien Epps Date: A few years ago
% Reference: Linde, Y., Buzo, A., and Gray, R. M. (1980). "An algorithm for vector quantiser
% design", IEEE Trans. Commun., vol. COM-28, no. 1, pp. 84-95, January.

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 45


Good programming practise
 Use pseudocode
% linfilt – plots various quantities for a digital filter

% Define filter
NumCoeff = [1 -2 1] % numerator coefficients
DenCoeff = 1; % denominator coefficients

% Plot frequency response


freqz(NumCoeff,DenCoeff);

% Plot pole-zero diagram


figure;
zplane(NumCoeff,DenCoeff);

% Plot impulse response


figure;
stem(NumCoeff); % filter is FIR

% Plot step response


figure;
Step = [zeros(1,100) ones(1,100)];
y = filter(NumCoeff,DenCoeff,Step);
plot(y);

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 46


Good programming practise
 Keep your code modular
– Use functions
 Bad:
for k = 1:N,
if sqrt(sum((x(k,:)-y).^2)) < min,
d(k) = sqrt(sum((x(k,:)-z).^2));
end
end

 Good:
for k = 1:N,
if dist(x(k,:),y) < min,
d(k) = dist(x(k,:),z);
end
end New function dist created by the programmer

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 47


Good programming practise

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 48


Good programming practise

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 49


Good programming practise

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 50


Good programming practise
 In this course:
– 10% of lab, project and assignment marks allocated
to good code formatting and programming practise
 Plenty of examples exist, see
http://www.datatool.com/downloads/matlab_style_guidelines.pdf
– 5% of lab and assignment marks allocated to
correct and effective use of plotting
 Correctly labelled axes
 Axis ranges selected to show interesting part of plot
 Good use of MATLAB plotting functions to visualise simulation
results
– e.g. Plotting two curves one same axis for easy
comparison
 Only the key essential information shown (not plot after plot of
similar results)

Dr Julien Epps ELEC2146 Electrical Engineering Modelling and Simulation 51


Object-Oriented Programming

see e.g.
http://www.cs.ubc.ca/~mdunham/tutorial/
Dr Julien Epps objectOriented.html
ELEC2146 Electrical Engineering Modelling and Simulation 52

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy