simulink and exercizes matlab coursebook

96
Sustainable Building and Systems Modeling 7Y700 Course Book Edited by dr. ir. ing. A.W.M. (Jos) van Schijndel 2011 Jan Copyright of included external Tutorials: An introduction to MatLab: David F. Griffiths, Dundee University SimuLink Tutorial: Arun Rajagopalan & Gregory Washington, Ohio State University Page 1 of 96

Upload: drughins

Post on 29-Dec-2015

110 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Simulink and Exercizes Matlab Coursebook

Sustainable

Building and Systems

Modeling

7Y700

Course Book

Edited by dr. ir. ing. A.W.M. (Jos) van Schijndel 2011 Jan Copyright of included external Tutorials: An introduction to MatLab: David F. Griffiths, Dundee University SimuLink Tutorial: Arun Rajagopalan & Gregory Washington, Ohio State University

Page 1 of 96

Page 2: Simulink and Exercizes Matlab Coursebook

Page 2 of 96

Page 3: Simulink and Exercizes Matlab Coursebook

Sustainable Building and Systems Modeling 7Y700

ECTS 3 (84 hours) Planning (hours): Lectures 10 Exercises in class 10 Exercises individual 30 Case study 34

Contents

First Block 1a. Introduction 1b. MatLab exercise 2a. Thermal systems modeling I 2b. ODE exercise 3a. Thermal systems modeling II 3b. SimuLink exercise 4a. HVAC modeling I 4b. SFunction exercise 5a. HVAC modeling II 5b. HVAC exercise 6a. Whole building modeling I 6b. Office Building in HAMBase I 7a. Whole building modeling II 7b. Office Building in HAMBase II 8a. Controllers modeling I 8b. Office Building in HAMBase-SimuLink

Second Block 9a. Controllers modeling II 9b. Application of a HVAC I 10a. Optimal control 10b. Application of a HVAC II 11. Case study 12. Case study 13. Case study

* deadline First report Case study * 14. Case study 15 Case study 16 Case study

Examination In block A & B in total 10 exercises provide training in modeling skills used for the final case studies. Each exercise will be examined with fulfilled yes/no. The course is examined by one case study including two reports. Each report will be assessed. The final grade is the mean with the limitation that each of these two grades has to be 6 or more. Lesson Materials Readers provided at the lectures http://sts.bwk.tue.nl/7y700/ Software package MatLab/SimuLink

Page 3 of 96

Page 4: Simulink and Exercizes Matlab Coursebook

Pre-knowledge (recommended) Course 7S801 Computational Building Physics and Systems using MatLab Course 7Y120 Energy usage and conversion Course Goal: The central theme is an introduction to sustainable building systems modeling and evaluation of these systems by estimations and simulations. Simulating is regarded as a skill. The knowledge gained during the lectures is applied at the exercises. The course goals are divided into knowledge, application and skill goals: skill goals: - learning to develop equation based models, - learning to implement self developed models in MatLab/SimuLink, - learning to use already developed models by others - learning to estimate energy related profits - learning to model and simulate sustainable building systems - learning to evaluate simulation results critically. application goals: - learning to apply the knowledge of sustainable building systems - learning to apply simulation software for design and evaluation of building systems knowledge goals: - gaining knowledge about sustainable building systems and practical applications Finally, the students are able to apply these methods and techniques independently by case studies.

Page 4 of 96

Page 5: Simulink and Exercizes Matlab Coursebook

Exercise 1, 7Y700 1) If you are not familiar with MatLab, take your time to study ‘An Introduction to Matlab’ at page 17 else proceed with (2) 2) Write a function in MatLab called ‘datagraf.m’ that reads and displays data of a text file using the function, load and plot commands. The text file is constructed as follows: The first column contains time steps; The second & third column contains measured values, i.e.: t1 x1 y1 t2 x2 y2 t3 x3 y3 .. .. .. tn xn yn With t1, t2..tn: time; x1, x2..xn and y1, y2..yn measured values An example-text file 'testdata.dat' can be found in the file ‘datfiles.zip’ : Summary Function: datagraf('filename') Input: 'filename' Output: graphical display of the contents of the file Send the mfile to: [email protected]

Page 5 of 96

Page 6: Simulink and Exercizes Matlab Coursebook

Exercise 2, 7Y700 1) If you are not familiar with implementing ODEs in MatLab, take your time to study

‘An example of solving ODEs in MatLab 7’ at page 54 else proceed with (2) 2) The following RC network is used in this exercise:

a) Derive system of ordinary differential equations (ODEs) for T1 and T2. b) Simulate this system of ODEs in MatLab. The start values of all temperatures

are equal to 0 oC; c) Check the stationary solution with a separate calculation of the temperatures by

hand and show that they are in agreement. Send the mfiles of Part 2b and the document containing the results of 2c to: [email protected]

40000 40000

0.04 2.5 0.13

Te = 0 Ti=20 T1 T2

Page 6 of 96

Page 7: Simulink and Exercizes Matlab Coursebook

Exercise 3, 7Y700 1) If you are not familiar with SimuLink, take your time to study ‘SimuLink Tutorial’

at page 57else proceed with (2) 2) Implement the following blocks in SimuLink;

and Simulate:

Send the mdl-file to: [email protected]

Page 7 of 96

Page 8: Simulink and Exercizes Matlab Coursebook

Exercise 4, 7Y700 1) Study the tutorial ‘Modeling & Simulation of a heat pump in SimuLink’ at page 88.

(You don’t have to send the solutions). 2) The following exercise is related with the RC network of Exercise 2.

a) Simulate the system (initial values equal 0) in SimuLink using an S-Function as

shown in following figure:

b) Compare the results with the results of exercise 2 or 4 and show they are in good

agreement Send the mdl & m file of parts 2a and a word/pdf file of part 2b to: [email protected]

Page 8 of 96

Page 9: Simulink and Exercizes Matlab Coursebook

Exercise 5, 7Y700

The goal of this exercise is to model and simulate a HVAC system. Later on this model will be integrated with a building model and controller.

km

(1-f)km

fkm

Q3 Q2

Q1

Figure 1. Top: HVAC system (= fig.1.7 from HVAC Controls systems, by C.P.

Underwood); Bottom schematic representation including air temperatures and heat flows.

Page 9 of 96

Page 10: Simulink and Exercizes Matlab Coursebook

1) Derive the missing ODEs for T1, T3, and T5 concerning the mathematical model representing the HVAC system:

...11 =dt

dTC

QwwTcmkTcmkdt

dTC +⋅⋅⋅−⋅⋅⋅=••

2122

...33 =dt

dTC

4)1(2244 TcmTicmkQTcmkdt

dTC ⋅⋅−⋅⋅−++⋅⋅⋅=•••

...55 =dt

dTC

with )2

212

3()( TTTTifKQww +−

+⋅=

2) Use as input: [Ti, Te, Q1, Q2, Q3]; Output: [T1, T2, T3, T4, T5, •

m *c*(T5-Ti)]

and estimate the parameters i.e. C1.. C5, •

m , c, k, f, K(f) 3) Implement this model in SimuLink using an S-Function 4) Simulate steady state conditions using Te=-10; Ti=20 and suitable values for Q1; Q2; Q3. Verify your results with calculations by hand. Send the files to: [email protected]

Page 10 of 96

Page 11: Simulink and Exercizes Matlab Coursebook

Exercise 6, 7Y700

1) Read the scientific background on HAMBase from:

http://archbps1.campus.tue.nl/bpswiki/index.php/Hamlab

2) Study the quick guide on how to start HAMBase:

http://archbps1.campus.tue.nl/bpswiki/index.php/Hamlab

3) Run the mfile 'startexample1.m'. Strip this 4-zone model into 1-zone model by

removing lines or placing comments. Save this file as 'Myexample1.m'. Check the

mfile by running it.

Send this mfile to: [email protected]

Page 11 of 96

Page 12: Simulink and Exercizes Matlab Coursebook

Exercise 7, 7Y700 1) Design or use an existing design of a so-called standard office zone. Include details on: Volume, orientation, constructions, glazing, internal gains (heat, moisture), schedules (i.e. profiles) 2) Adapt the last HAMBase model of exercise 6 using the details of your standard office design. Save this file as 'office1.m'. Check the mfile by running it. 3) Calculate the required energy for heating & cooling in [kWh] and the peaking heating & cooling power in [kW]. Create a Climate Evaluation Chart (CEC) for the indoor climate. You can simulate the characteristics of a standard Dutch office now! Send the files to: [email protected]

Page 12 of 96

Page 13: Simulink and Exercizes Matlab Coursebook

Exercise 8, 7Y700

1) Study the quick guide on how to export a HAMBase model to SimuLink from:

http://archbps1.campus.tue.nl/bpswiki/index.php/Hamlab

2) Export the last HAMBase (MatLab) model of exercise 7 ('office1.m') to SimuLink.

Save as ‘office1S.mdl’. Check the mdl-file by running it. Note that SimuLink model is a

so-called free-floating model without any heating, cooling & (de)humidification.

3) Add the necessary on/off controller(s) for heating, cooling & (de)humidification

using ‘Relay’ blocks in SimuLink, to reproduce approximately the original MatLab

results using ‘office1.m’. Save as ‘office1SC.mdl’.

4) Show that the HAMBase MatLab model ‘office1.m’ and the HAMBase SimuLink

model ‘office1SC.mdl’ give approximately the same indoor climate.

Send the mdl file of 3 and a document containing the results of 4 to: [email protected]

Page 13 of 96

Page 14: Simulink and Exercizes Matlab Coursebook

Exercise 9 & 10 (combined), 7Y700 1) Couple the free floating HAMBase SimuLink model ‘office1S.mdl’ of exercise 8 with the SimuLink HVAC model of exercise 5. 2) Add the necessary controller(s) for heating & cooling (i.e. Q1, Q2 & Q3, see figure 1 of Exercise 5) in order to create workable system. 3) Optimize your controllers in such a way that the energy needed is minimized under an acceptable indoor climate. Send the mdl file and a document containing the results of 3 to: [email protected]

Page 14 of 96

Page 15: Simulink and Exercizes Matlab Coursebook

7Y700 Case Study

Introduction In this case study, the models will be built from scratch! The main idea is that you provide your own case study based on an existing building (for example your house, office, sports hall etc.) including its systems. Furthermore your case study consists of two parts on the modeling and simulation of the energy usage of: (1) the existing situation and (2) a new situation including improved & sustainable integrated measures for the building and systems How to start 1) Discuss your idea with the supervisor for starting part 1 approval as soon as possible Planning (week 11): Prepare your the building modeling (i.e. number zones; construction details, ventilation, sources, etc. ) (week 12): Simulate the existing building, compare your simulated energy use with real data from the building or with an estimated energy use (week 13): Collect and/or Prepare your models, needed for the improved measures (i.e. ODEs, S-Functions, SimuLink Blocks). **** Report current work using the Case study PowerPoint template poster ***** (week 14): Discuss your work so far with the supervisor for starting part 2 approval as soon as possible. Start implementing the new measures (week 15) : Modeling & Simulation of the new design (week 16) : Modeling & Simulation of the new design, start Reporting (See below) Modeling & Simulation Considerations 2a) What are the objectives of the case study? 2b) Which models do you intend to use? 2c) Provide descriptions of all models, including details of the implementation and

verification of new models (i.e. models that are not used during the course) 2d) Evaluate your simulation results 2e) Evaluate your model on how realistic it is. Is it useful for design? 2f) Optimize at least one parameter of the model. Report 3a) Report of your findings using maximum 6 pages exclusive appendices 3b) Complete the Case study PowerPoint template poster Send all files including the report (in pdf), poster (in pdf) & MatLab/SimuLink files in a single zip file to: [email protected]

Page 15 of 96

Page 16: Simulink and Exercizes Matlab Coursebook

Title

Subtitle

Name:

Master:

/ 7Y700 Sustainable Building and Systems Modeling

Existing Building and Systems

Description Put text here…

Figure 1. A picture of the building and its systems

Simulated current energy usagePut text here …

Figure 2. Overview of the results of the simulated energy usage

Comparison with real data and/or estimationsPut text here …

Figure 3. Overview of the results

Put text here …

Put your photo here

New Sustainable Measures

Description of the modelsPut text here …

Figure 4. An overview of the models

The integrated model in SimuLink Put text here …

Figure 5. An overview of the integrated model in SimuLink

Simulated improved energy usage Put text here …

Figure 6. Overview of the results

Put text here …

Page 16 of 96

Page 17: Simulink and Exercizes Matlab Coursebook

An Introduction to Matlab

Version 2.3

David F. Griffiths

Department of Mathematics

The UniversityDundee DD1 4HN

With additional material by Ulf CarlssonDepartment of Vehicle Engineering

KTH, Stockholm, Sweden

Copyright c©1996 by David F. Griffiths. Amended October, 1997, August 2001, September 2005.This introduction may be distributed provided that it is not be altered in any way and that its sourceis properly and completely specified.

Page 17 of 96

Page 18: Simulink and Exercizes Matlab Coursebook

Contents

1 MATLAB 2

2 Starting Up 22.1 Windows Systems . . . . . . . . . . 22.2 Unix Systems . . . . . . . . . . . . . 22.3 Command Line Help . . . . . . . . . 22.4 Demos . . . . . . . . . . . . . . . . . 3

3 Matlab as a Calculator 3

4 Numbers & Formats 3

5 Variables 35.1 Variable Names . . . . . . . . . . . . 3

6 Suppressing output 4

7 Built–In Functions 47.1 Trigonometric Functions . . . . . . . 47.2 Other Elementary Functions . . . . . 4

8 Vectors 48.1 The Colon Notation . . . . . . . . . 58.2 Extracting Bits of a Vector . . . . . 58.3 Column Vectors . . . . . . . . . . . . 58.4 Transposing . . . . . . . . . . . . . . 5

9 Keeping a record 6

10 Plotting Elementary Functions 610.1 Plotting—Titles & Labels . . . . . . 710.2 Grids . . . . . . . . . . . . . . . . . . 710.3 Line Styles & Colours . . . . . . . . 710.4 Multi–plots . . . . . . . . . . . . . . 710.5 Hold . . . . . . . . . . . . . . . . . . 710.6 Hard Copy . . . . . . . . . . . . . . 810.7 Subplot . . . . . . . . . . . . . . . . 810.8 Zooming . . . . . . . . . . . . . . . . 810.9 Formatted text on Plots . . . . . . . 810.10Controlling Axes . . . . . . . . . . . 9

11 Keyboard Accelerators 9

12 Copying to and from Word and otherapplications 1012.1 Window Systems . . . . . . . . . . . 1012.2 Unix Systems . . . . . . . . . . . . . 10

13 Script Files 10

14 Products, Division & Powers of Vec-tors 1114.1 Scalar Product (*) . . . . . . . . . . 1114.2 Dot Product (.*) . . . . . . . . . . . 1114.3 Dot Division of Arrays (./) . . . . . 1214.4 Dot Power of Arrays (.^) . . . . . . 12

15 Examples in Plotting 13

16 Matrices—Two–Dimensional Arrays 1316.1 Size of a matrix . . . . . . . . . . . . 1416.2 Transpose of a matrix . . . . . . . . 1416.3 Special Matrices . . . . . . . . . . . 1416.4 The Identity Matrix . . . . . . . . . 1416.5 Diagonal Matrices . . . . . . . . . . 1516.6 Building Matrices . . . . . . . . . . . 1516.7 Tabulating Functions . . . . . . . . . 1516.8 Extracting Bits of Matrices . . . . . 1616.9 Dot product of matrices (.*) . . . . 1616.10Matrix–vector products . . . . . . . 1616.11Matrix–Matrix Products . . . . . . . 1716.12Sparse Matrices . . . . . . . . . . . . 17

17 Systems of Linear Equations 1817.1 Overdetermined system of linear equa-

tions . . . . . . . . . . . . . . . . . . 18

18 Characters, Strings and Text 20

19 Loops 20

20 Logicals 2120.1 While Loops . . . . . . . . . . . . . . 2220.2 if...then...else...end . . . . . . 23

21 Function m–files 2321.1 Examples of functions . . . . . . . . 24

22 Further Built–in Functions 2522.1 Rounding Numbers . . . . . . . . . . 2522.2 The sum Function . . . . . . . . . . . 2522.3 max & min . . . . . . . . . . . . . . . 2622.4 Random Numbers . . . . . . . . . . 2622.5 find for vectors . . . . . . . . . . . . 2722.6 find for matrices . . . . . . . . . . . 27

23 Plotting Surfaces 27

24 Timing 28

25 On–line Documentation 29

26 Reading and Writing Data Files 2926.1 Formatted Files . . . . . . . . . . . . 3026.2 Unformatted Files . . . . . . . . . . 30

27 Graphic User Interfaces 31

28 Command Summary 32

1

Page 18 of 96

Page 19: Simulink and Exercizes Matlab Coursebook

1 MATLAB

• Matlab is an interactive system for doing nu-merical computations.

• A numerical analyst called Cleve Moler wrotethe first version of Matlab in the 1970s. Ithas since evolved into a successful commercialsoftware package.

• Matlab relieves you of a lot of the mundanetasks associated with solving problems nu-merically. This allows you to spend more timethinking, and encourages you to experiment.

• Matlab makes use of highly respected algo-rithms and hence you can be confident aboutyour results.

• Powerful operations can be performed usingjust one or two commands.

• You can build up your own set of functionsfor a particular application.

• Excellent graphics facilities are available, andthe pictures can be inserted into LATEX andWord documents.

These notes provide only a brief glimpse of thepower and flexibility of the Matlab system. For amore comprehensive view we recommend the book

Matlab GuideD.J. Higham & N.J. Higham

SIAM Philadelphia, 2000, ISBN: 0-89871-469-9.

2 Starting Up

2.1 Windows Systems

On Windows systems MATLAB is started by double-clicking the MATLAB icon on the desktop or byselecting MATLAB from the start menu.The starting procedure takes the user to the Com-mand window where the Command line is indicatedwith ’>>’. Used in the calculator mode all Matlabcommands are entered to the command line fromthe keyboard.Matlab can be used in a number of different ways ormodes; as an advanced calculator in the calculatormode, in a high level programming language modeand as a subroutine called from a C-program. Moreinformation on the first two of these modes is givenbelow.Help and information on Matlab commands can befound in several ways,

• from the command line by using the ’helptopic’ command (see below),

• from the separate Help window found underthe Help menu or

• from the Matlab helpdesk stored on disk oron a CD-ROM.

Another useful facility is to use the ’lookfor keyword’command, which searches the help files for the key-word. See Exercise 16.1 (page 17) for an exampleof its use.

2.2 Unix Systems

• You should have a directory reserved for sav-ing files associated with Matlab. Create sucha directory (mkdir) if you do not have one.Change into this directory (cd).

• Start up a new xterm window (do xterm & inthe existing xterm window).

• Launch Matlab in one of the xterm windowswith the command

matlab

After a short pause, the logo will be shownfollowed by a window containing the Matlabinterface. Should you wish to run Matlab inan xterm window, use the command

matlab -nojvm

and, following dislpay of the logo, the Matlabprompt >> will appear.

Type quit at any time to exit from Mat-lab.

2.3 Command Line Help

Help is available from the command line prompt.Type help help for “help” (which gives a brief syn-opsis of the help system), help for a list of topics.The first few lines of this read

HELP topics:

matlab/general - General purpose commands.

matlab/ops - Operators and special char...

matlab/lang - Programming language const...

matlab/elmat - Elementary matrices and ma...

matlab/elfun - Elementary math functions.

matlab/specfun - Specialized math functions.

(truncated lines are shown with . . . ). Then to ob-tain help on “Elementary math functions”, for instance,type

>> help elfun

2

Page 19 of 96

Page 20: Simulink and Exercizes Matlab Coursebook

This gives rather a lot of information so, in order to seethe information one screenful at a time, first issue thecommand more on, i.e.,

>> more on

>> help elfun

Hit any key to progress to the next page of information.

2.4 Demos

Demonstrations are invaluable since they give an indi-cation of Matlabs capabilities. A comprehensive set areavailable by typing the command

>> demo

( Warning: this will clear the values of all current vari-ables.)

3 Matlab as a Calculator

The basic arithmetic operators are + - * / ^ and theseare used in conjunction with brackets: ( ). The symbol^ is used to get exponents (powers): 2^4=16.You should type in commands shown followingthe prompt: >>.

>> 2 + 3/4*5

ans =

5.7500

>>

Is this calculation 2 + 3/(4*5) or 2 + (3/4)*5? Mat-lab works according to the priorities:

1. quantities in brackets,

2. powers 2 + 3^2 ⇒2 + 9 = 11,

3. * /, working left to right (3*4/5=12/5),

4. + -, working left to right (3+4-5=7-5),

Thus, the earlier calculation was for 2 + (3/4)*5 bypriority 3.

4 Numbers & Formats

Matlab recognizes several different kinds of numbers

Type ExamplesInteger 1362,−217897Real 1.234,−10.76Complex 3.21− 4.3i (i =

√−1)

Inf Infinity (result of dividing by 0)NaN Not a Number, 0/0

The “e” notation is used for very large or very smallnumbers:-1.3412e+03 = −1.3412× 103 = −1341.2-1.3412e-01 = −1.3412× 10−1 = −0.13412All computations in MATLAB are done in double pre-cision, which means about 15 significant figures. The

Command Example of Output>>format short 31.4162(4–decimal places)>>format short e 3.1416e+01>>format long e 3.141592653589793e+01>>format short 31.4162(4–decimal places)>>format bank 31.42(2–decimal places)

format—how Matlab prints numbers—is controlled bythe “format” command. Type help format for full list.Should you wish to switch back to the default formatthen format will suffice.The command

format compact

is also useful in that it suppresses blank lines in theoutput thus allowing more information to be displayed.

5 Variables

>> 3-2^4

ans =

-13

>> ans*5

ans =

-65

The result of the first calculation is labelled “ans” byMatlab and is used in the second calculation where itsvalue is changed.We can use our own names to store numbers:

>> x = 3-2^4

x =

-13

>> y = x*5

y =

-65

so that x has the value −13 and y = −65. These canbe used in subsequent calculations. These are examplesof assignment statements: values are assigned tovariables. Each variable must be assigned a value beforeit may be used on the right of an assignment statement.

5.1 Variable Names

Legal names consist of any combination of letters anddigits, starting with a letter. These are allowable:

NetCost, Left2Pay, x3, X3, z25c5

These are not allowable:

Net-Cost, 2pay, %x, @sign

Use names that reflect the values they represent.Special names: you should avoid usingeps = 2.2204e-16 = 2−54 (The largest number suchthat 1 + eps is indistinguishable from 1) andpi = 3.14159... = π.If you wish to do arithmetic with complex numbers,bothi and j have the value

√−1 unless you change them

3

Page 20 of 96

Page 21: Simulink and Exercizes Matlab Coursebook

>> i,j, i=3

ans = 0 + 1.0000i

ans = 0 + 1.0000i

i = 3

6 Suppressing output

One often does not want to see the result of intermedi-ate calculations—terminate the assignment statementor expression with semi–colon

>> x=-13; y = 5*x, z = x^2+y

y =

-65

z =

104

>>

the value of x is hidden. Note also we can place severalstatements on one line, separated by commas or semi–colons.

Exercise 6.1 In each case find the value of the expres-sion in Matlab and explain precisely the order in whichthe calculation was performed.

i) -2^3+9 ii) 2/3*3

iii) 3*2/3 iv) 3*4-5^2*2-3

v) (2/3^2*5)*(3-4^3)^2 vi) 3*(3*4-2*5^2-3)

7 Built–In Functions

7.1 Trigonometric Functions

Those known to Matlab aresin, cos, tan

and their arguments should be in radians.e.g. to work out the coordinates of a point on a circle ofradius 5 centred at the origin and having an elevation30o = π/6 radians:

>> x = 5*cos(pi/6), y = 5*sin(pi/6)

x =

4.3301

y =

2.5000

The inverse trig functions are called asin, acos, atan

(as opposed to the usual arcsin or sin−1 etc.). Theresult is in radians.

>> acos(x/5), asin(y/5)

ans = 0.5236

ans = 0.5236

>> pi/6

ans = 0.5236

7.2 Other Elementary Functions

These include sqrt, exp, log, log10

>> x = 9;

>> sqrt(x),exp(x),log(sqrt(x)),log10(x^2+6)

ans =

3

ans =

8.1031e+03

ans =

1.0986

ans =

1.9395

exp(x) denotes the exponential function exp(x) = ex

and the inverse function is log:

>> format long e, exp(log(9)), log(exp(9))

ans = 9.000000000000002e+00

ans = 9

>> format short

and we see a tiny rounding error in the first calculation.log10 gives logs to the base 10. A more complete listof elementary functions is given in Table 2 on page 32.

8 Vectors

These come in two flavours and we shall first describerow vectors: they are lists of numbers separated by ei-ther commas or spaces. The number of entries is knownas the “length” of the vector and the entries are oftenreferred to as “elements” or “components” of the vec-tor.The entries must be enclosed in square brackets.

>> v = [ 1 3, sqrt(5)]

v =

1.0000 3.0000 2.2361

>> length(v)

ans =

3

Spaces can be vitally important:

>> v2 = [3+ 4 5]

v2 =

7 5

>> v3 = [3 +4 5]

v3 =

3 4 5

We can do certain arithmetic operations with vectorsof the same length, such as v and v3 in the previoussection.

>> v + v3

ans =

4.0000 7.0000 7.2361

>> v4 = 3*v

v4 =

3.0000 9.0000 6.7082

>> v5 = 2*v -3*v3

v5 =

-7.0000 -6.0000 -10.5279

>> v + v2

??? Error using ==> +

Matrix dimensions must agree.

4

Page 21 of 96

Page 22: Simulink and Exercizes Matlab Coursebook

i.e. the error is due to v and v2 having different lengths.A vector may be multiplied by a scalar (a number—see v4 above), or added/subtracted to another vectorof the same length. The operations are carried outelementwise.We can build row vectors from existing ones:

>> w = [1 2 3], z = [8 9]

>> cd = [2*z,-w], sort(cd)

w =

1 2 3

z =

8 9

cd =

16 18 -1 -2 -3

ans =

-3 -2 -1 16 18

Notice the last command sort’ed the elements of cd

into ascending order.We can also change or look at the value of particularentries

>> w(2) = -2, w(3)

w =

1 -2 3

ans =

3

8.1 The Colon Notation

This is a shortcut for producing row vectors:

>> 1:4

ans =

1 2 3 4

>> 3:7

ans =

3 4 5 6 7

>> 1:-1

ans =

[]

More generally a : b : c produces a vector of entriesstarting with the value a, incrementing by the value buntil it gets to c (it will not produce a value beyond c).This is why 1:-1 produced the empty vector [].

>> 0.32:0.1:0.6

ans =

0.3200 0.4200 0.5200

>> -1.4:-0.3:-2

ans =

-1.4000 -1.7000 -2.0000

8.2 Extracting Bits of a Vector

>> r5 = [1:2:6, -1:-2:-7]

r5 =

1 3 5 -1 -3 -5 -7

To get the 3rd to 6th entries:

>> r5(3:6)

ans =

5 -1 -3 -5

To get alternate entries:

>> r5(1:2:7)

ans =

1 5 -3 -7

What does r5(6:-2:1) give?See help colon for a fuller description.

8.3 Column Vectors

These have similar constructs to row vectors. Whendefining them, entries are separated by ; or “newlines”

>> c = [ 1; 3; sqrt(5)]

c =

1.0000

3.0000

2.2361

>> c2 = [3

4

5]

c2 =

3

4

5

>> c3 = 2*c - 3*c2

c3 =

-7.0000

-6.0000

-10.5279

so column vectors may be added or subtracted pro-vided that they have the same length.

8.4 Transposing

We can convert a row vector into a column vector (andvice versa) by a process called transposing—denoted by’.

>> w, w’, c, c’

w =

1 -2 3

ans =

1

-2

3

c =

1.0000

3.0000

2.2361

ans =

1.0000 3.0000 2.2361

>> t = w + 2*c’

t =

3.0000 4.0000 7.4721

>> T = 5*w’-2*c

T =

3.0000

5

Page 22 of 96

Page 23: Simulink and Exercizes Matlab Coursebook

-16.0000

10.5279

If x is a complex vector, then x’ gives the complex con-jugate transpose of x:

>> x = [1+3i, 2-2i]

ans =

1.0000 + 3.0000i 2.0000 - 2.0000i

>> x’

ans =

1.0000 - 3.0000i

2.0000 + 2.0000i

Note that the components of x were defined withouta * operator; this means of defining complex numbersworks even when the variable i already has a numericvalue. To obtain the plain transpose of a complex num-ber use .’ as in

>> x.’

ans =

1.0000 + 3.0000i

2.0000 - 2.0000i

9 Keeping a record

Issuing the command

>> diary mysession

will cause all subsequent text that appears on the screento be saved to the file mysession located in the direc-tory in which Matlab was invoked. You may use anylegal filename except the names on and off. The recordmay be terminated by

>> diary off

The file mysession may be edited with your favouriteeditor (the Matlab editor, emacs, or even Word) to re-move any mistakes.If you wish to quit Matlab midway through a calcula-tion so as to continue at a later stage:

>> save thissession

will save the current values of all variables to a filecalled thissession.mat. This file cannot be edited.When you next startup Matlab, type

>> load thissession

and the computation can be resumed where you left off.A list of variables used in the current session may beseen with

>> whos

See help whos and help save.

>> whos

Name Size Elements Bytes Density Complex

ans 1 by 1 1 8 Full No

v 1 by 3 3 24 Full No

v1 1 by 2 2 16 Full No

v2 1 by 2 2 16 Full No

v3 1 by 3 3 24 Full No

v4 1 by 3 3 24 Full No

x 1 by 1 1 8 Full No

y 1 by 1 1 8 Full No

Grand total is 16 elements using 128 bytes

10 Plotting Elementary Func-tions

Suppose we wish to plot a graph of y = sin 3πx for0 ≤ x ≤ 1. We do this by sampling the function ata sufficiently large number of points and then joiningup the points (x, y) by straight lines. Suppose we takeN + 1 points equally spaced a distance h apart:

>> N = 10; h = 1/N; x = 0:h:1;

defines the set of points x = 0, h, 2h, . . . , 1−h, 1. Alter-nately, we may use the command linspace: The gen-eral form of the command is linspace (a,b,n) whichgenerates n+ 1 equispaced points between a and b, in-clusive. So, in this case we would use the command

>> x = linspace (0,1,11);

The corresponding y values are computed by

>> y = sin(3*pi*x);

and finally, we can plot the points with

>> plot(x,y)

The result is shown in Figure 1, where it is clear thatthe value of N is too small.

Figure 1: Graph of y = sin 3πx for 0 ≤ x ≤ 1 usingh = 0.1.

On changing the value of N to 100:

>> N = 100; h = 1/N; x = 0:h:1;

>> y = sin(3*pi*x); plot(x,y)

we get the picture shown in Figure 2.

6

Page 23 of 96

Page 24: Simulink and Exercizes Matlab Coursebook

Figure 2: Graph of y = sin 3πx for 0 ≤ x ≤ 1 usingh = 0.01.

10.1 Plotting—Titles & Labels

To put a title and label the axes, we use

>> title(’Graph of y = sin(3pi x)’)

>> xlabel(’x axis’)

>> ylabel(’y-axis’)

The strings enclosed in single quotes, can be anythingof our choosing. Some simple LATEX commands areavailable for formatting mathematical expressions andGreek characters—see Section 10.9.See also ezplot the “Easy to use function plotter”.

10.2 Grids

A dotted grid may be added by

>> grid

This can be removed using either grid again, or grid

off.

10.3 Line Styles & Colours

The default is to plot solid lines. A solid white line isproduced by

>> plot(x,y,’w-’)

The third argument is a string whose first characterspecifies the colour(optional) and the second the linestyle. The options for colours and styles are:

Colours Line Styles

y yellow . pointm magenta o circlec cyan x x-markr red + plusg green - solidb blue * starw white : dottedk black -. dashdot

-- dashed

The number of available plot symbols is wider thanshown in this table. Use help plot to obtain a fulllist. See also help shapes.

10.4 Multi–plots

Several graphs may be drawn on the same figure as in

>> plot(x,y,’w-’,x,cos(3*pi*x),’g--’)

A descriptive legend may be included with

>> legend(’Sin curve’,’Cos curve’)

which will give a list of line–styles, as they appearedin the plot command, followed by a brief description.Matlab fits the legend in a suitable position, so as notto conceal the graphs whenever possible.For further information do help plot etc.The result of the commands

>> plot(x,y,’w-’,x,cos(3*pi*x),’g--’)

>> legend(’Sin curve’,’Cos curve’)

>> title(’Multi-plot ’)

>> xlabel(’x axis’), ylabel(’y axis’)

>> grid

is shown in Figure 3. The legend may be moved man-ually by dragging it with the mouse.

Figure 3: Graph of y = sin 3πx and y = cos 3πx for0 ≤ x ≤ 1 using h = 0.01.

10.5 Hold

A call to plot clears the graphics window before plot-ting the current graph. This is not convenient if wewish to add further graphics to the figure at some laterstage. To stop the window being cleared:

>> plot(x,y,’w-’), hold on

>> plot(x,y,’gx’), hold off

“hold on” holds the current picture; “hold off” re-leases it (but does not clear the window, which can bedone with clf). “hold” on its own toggles the holdstate.

7

Page 24 of 96

Page 25: Simulink and Exercizes Matlab Coursebook

10.6 Hard Copy

To obtain a printed copy select Print from the Filemenu on the Figure toolbar.Alternatively one can save a figure to a file for laterprinting (or editing). A number of formats is avail-able (use help print to obtain a list). To save a filein “Encapsulated PostScript” format, issue the Matlabcommand

print -deps fig1

which will save a copy of the image in a file calledfig1.eps.

10.7 Subplot

The graphics window may be split into an m× n arrayof smaller windows into which we may plot one or moregraphs. The windows are counted 1 to mn row–wise,starting from the top left. Both hold and grid work onthe current subplot.

>> subplot(221), plot(x,y)

>> xlabel(’x’),ylabel(’sin 3 pi x’)

>> subplot(222), plot(x,cos(3*pi*x))

>> xlabel(’x’),ylabel(’cos 3 pi x’)

>> subplot(223), plot(x,sin(6*pi*x))

>> xlabel(’x’),ylabel(’sin 6 pi x’)

>> subplot(224), plot(x,cos(6*pi*x))

>> xlabel(’x’),ylabel(’cos 6 pi x’)

subplot(221) (or subplot(2,2,1)) specifies that thewindow should be split into a 2× 2 array and we selectthe first subwindow.

10.8 Zooming

We often need to “zoom in” on some portion of a plotin order to see more detail. Clicking on the “Zoom in”or “Zoom out” button on the Figure window is simplestbut one can also use the command

>> zoom

Pointing the mouse to the relevant position on the plotand clicking the left mouse button will zoom in by a

factor of two. This may be repeated to any desiredlevel.Clicking the right mouse button will zoom out by afactor of two.Holding down the left mouse button and dragging themouse will cause a rectangle to be outlined. Releasingthe button causes the contents of the rectangle to fillthe window.zoom off turns off the zoom capability.

Exercise 10.1 Draw graphs of the functions

y = cosx

y = x

for 0 ≤ x ≤ 2 on the same window. Use the zoom fa-cility to determine the point of intersection of the twocurves (and, hence, the root of x = cosx) to two signif-icant figures.

The command clf clears the current figure while close

1 will close the window labelled “Figure 1”. To opena new figure window type figure or, to get a windowlabelled “Figure 9”, for instance, type figure (9). If“Figure 9” already exists, this command will bring thiswindow to the foreground and the result subsequentplotting commands will be drawn on it.

10.9 Formatted text on Plots

It is possible to change to format of text on plots soas to increase or decrease its size and also to typesetsimple mathematical expressions (in LATEX form).We shall give two illustrations.First we plot the first 100 terms in the sequence xngiven by xn =

(1 + 1

n

)nand then graph the function

φ(x) = x3 sin2(3πx) on the interval −1 ≤ x ≤ 1. Thecommands

>> set(0,’Defaultaxesfontsize’,16);

>> n = 1:100; x = (1+1./n).^n;

>> subplot (211)

>> plot(n,x,’.’,[0 max(n)],exp(1)*[1 1],...

’--’,’markersize’,8)

>> title(’x_n = (1+1/n)^n’,’fontsize’,12)

>> xlabel(’n’), ylabel(’x_n’)

>> legend(’x_n’,’y = e^1 = 2.71828...’,4)

>> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

>> subplot (212)

>> x = -2:.02:2; y = x.^3.*sin(3*pi*x).^2;

>> plot(x,y,’linewidth’,2)

>> legend(’y = x^3sin^2 3\pi x’,4)

>> xlabel(’x’)

produce the graph shown below. The salient featuresof these commands are

1. The first line increases the size of the default fontsize used for the axis labels, legends and titles.

2. The size of the plot symbol “.” is changed fromthe default (6) to size 8 by the additional stringfollowed by value “’markersize’,8”.

8

Page 25 of 96

Page 26: Simulink and Exercizes Matlab Coursebook

3. The strings x_n are formatted as xn to give sub-scripts while x^3 leads to superscripts x3.

Note also that sin23πx translates into the Matlabcommand sin(3*pi*x).^2—the position of theexponent is different.

4. Greek characters α, β, . . . , ω,Ω are produced bythe strings ’\alpha’, ’\beta’, . . . ,’\omega’, ’\Omega’.the integral symbol:

∫is produced by ’\int’.

5. The thickness of the line used in the lower graphis changed from its default value (0.5) to 2.

6. Use help legend to determine the meaning ofthe last argument in the legend commands.

One can determine the current value of any plot prop-erty by first obtaining its “handle number” and thenusing the get command such as

>> handle = plot (x,y,’.’)

>> get (handle,’markersize’)

ans =

6

Experiment also with set (handle) (which will listpossible values for each property) andset(handle,’markersize’,12)

which will increase the size of the marker (a dot in thiscase) to 12. Also, all plot properties can be edited from

the Figure window by selecting the Tools menu fromthe toolbar. For instance, to change the linewidth

of a graph, first select the curve by double clicking(it should then change its appearance) and then select

Line Properties. . . from the Tools . This will pop

up a dialogue window from which the width, colour,style,. . . of the curve may be changed.

10.10 Controlling Axes

Once a plot has been created in the graphics windowyou may wish to change the range of x and y valuesshown on the picture.

>> clf, N = 100; h = 1/N; x = 0:h:1;

>> y = sin(3*pi*x); plot(x,y)

>> axis([-0.5 1.5 -1.2 1.2]), grid

The axis command has four parameters, the first twoare the minimum and maximum values of x to use onthe axis and the last two are the minimum and maxi-mum values of y. Note the square brackets. The resultof these commands is shown in Figure 4. Look at help

axis and experiment with the commands axis equal,axis verb, axis square, axis normal, axis tight inany order.

Figure 4: The effect of changing the axes of a plot.

11 Keyboard Accelerators

One can recall previous Matlab commands by using the↑ and ↓ cursor keys. Repeatedly pressing ↑ will reviewthe previous commands (most recent first) and, if youwant to re-execute the command, simply press the re-turn key.To recall the most recent command starting with p, say,type p at the prompt followed by ↑. Similarly, typingpr followed by ↑ will recall the most recent commandstarting with pr.Once a command has been recalled, it may be edited(changed). You can use ← and → to move backwardsand forwards through the line, characters may be in-serted by typing at the current cursor position or deletedusing the Del key. This is most commonly used whenlong command lines have been mistyped or when youwant to re–execute a command that is very similar toone used previously.The following emacs–like commands may also be used:

cntrl a move to start of linecntrl e move to end of linecntrl f move forwards one charactercntrl b move backwards one charactercntrl d delete character under the cursor

Once you have the command in the required form, pressreturn.

Exercise 11.1 Type in the commands

9

Page 26 of 96

Page 27: Simulink and Exercizes Matlab Coursebook

>> x = -1:0.1:1;

>> plot(x,sin(pi*x),’w-’)

>> hold on

>> plot(x,cos(pi*x),’r-’)

Now use the cursor keys with suitable editing to execute:

>> x = -1:0.05:1;

>> plot(x,sin(2*pi*x),’w-’)

>> plot(x,cos(2*pi*x),’r-.’), hold off

12 Copying to and from Wordand other applications

There are many situations where one wants to copythe output resulting from a Matlab command (or com-mands) into a Windows application such as Word orinto a Unix file editor such as “emacs” or “vi”.

12.1 Window Systems

Copying material is made possible on the Windows op-erating system by using the Windows clipboard.Also, pictures can be exported to files in a number ofalternative formats such as encapsulated postscript for-mat or in jpeg format. Matlab is so frequently used asan analysis tool that many manufacturers of measure-ment systems and software find it convenient to pro-vide interfaces to Matlab which make it possible, forinstance, to import measured data directly into a *.mat

Matlab file (see load and save in Section 9).

Example 12.1 Copying a figure into Word.

Diagrams prepared in Matlab are easily exported toother Windows applications such as Word. Supposea plot of the functions sin(2πft) and sin(2πft + π/4),with f = 100, is needed in a report written in Word.We create a time vector, t, with 500 points distributedover 5 periods and then evaluate and plot the two func-tion vectors.

>> t = [1:1:500]/500/20;

>> f = 100;

>> y1 = sin(2*pi*f*t);

>> y2 = sin(2*pi*f*t+pi/4);

>> plot(t,y1,’-’,t,y2,’--’);

>> axis([0 0.05 -1.5 1.5]);

>> grid

In order to copy the plot into a Word document

• Select “Copy Figure” under the Edit menu onthe figure windows toolbar.

• Switch to the Word application if it is alreadyrunning, otherwise open a Word document.

• Place the cursor in the desired position in thedocument and select “Paste” under the “Edit”menu in the Word tool bar.

12.2 Unix Systems

In order to carry out the following exercise, you shouldhave Matlab running in one window and either Emacsor Vi running in another.To copy material from one window to another, (herel means click Left Mouse Button, etc)

First select the material to copy by l on the start of thematerial you want and then either dragging the mouse(with the buttom down) to highlight the text, or r atthe end of the material. Next move the mouse into theother window and l at the location you want the textto appear. Finally, click the m .When copying from another application into Matlabyou can only copy material to the prompt line. OnUnix systems figures are normally saved in files (seeSection 10.6) which are then imported into other doc-uments.

13 Script Files

Script files are normal ASCII (text) files that containMatlab commands. It is essential that such files havenames having an extension .m (e.g., Exercise4.m) and,for this reason, they are commonly known as m-files.The commands in this file may then be executed using>> Exercise4

Note: the command does not include the file name ex-tension .m.It is only the output from the commands (and not thecommands themselves) that are displayed on the screen.Script files are created with your favourite editor underUnix while, under Windows, click on the “New Docu-ment” icon at the top left of the main Matlab windowto pop up a new window showing the “M-file Editor”.Type in your commands and then save (to a file with a.m extension).To see the commands in the command window prior totheir execution:>> echo on

and echo off will turn echoing off.Any text that follows % on a line is ignored. The mainpurpose of this facility is to enable comments to beincluded in the file to describe its purpose.To see what m-files you have in your current directory,use>> what

Exercise 13.1 1. Type in the commands from §10.7into a file called exsub.m.

2. Use what to check that the file is in the correctarea.

3. Use the command type exsub to see the contentsof the file.

4. Execute these commands.

See §21 for the related topic of function files.

10

Page 27 of 96

Page 28: Simulink and Exercizes Matlab Coursebook

14 Products, Division & Pow-ers of Vectors

14.1 Scalar Product (*)

We shall describe two ways in which a meaning may beattributed to the product of two vectors. In both casesthe vectors concerned must have the same length.The first product is the standard scalar product. Sup-pose that u and v are two vectors of length n, u beinga row vector and v a column vector:

u = [u1, u2, . . . , un] , v =

v1

v2

...vn

.The scalar product is defined by multiplying the corre-sponding elements together and adding the results togive a single number (scalar).

u v =

n∑i=1

uivi.

For example, if u = [10,−11, 12], and v =

[20−21−22

]then n = 3 and

u v = 10× 20 + (−11)× (−21) + 12× (−22) = 167.

We can perform this product in Matlab by

>> u = [ 10, -11, 12], v = [20; -21; -22]

>> prod = u*v % row times column vector

Suppose we also define a row vector w and a columnvector z by

>> w = [2, 1, 3], z = [7; 6; 5]

w =

2 1 3

z =

7

6

5

and we wish to form the scalar products of u with w

and v with z.

>> u*w

??? Error using ==> *

Inner matrix dimensions must agree.

an error results because w is not a column vector. Recallfrom page 5 that transposing (with ’) turns columnvectors into row vectors and vice versa.

So, to form the scalar product of two row vectors or twocolumn vectors,

>> u*w’ % u & w are row vectors

ans =

45

>> u*u’ % u is a row vector

ans =

365

>> v’*z % v & z are column vectors

ans =

-96

We shall refer to the Euclidean length of a vector as thenorm of a vector; it is denoted by the symbol ‖u‖ anddefined by

‖u‖ =

√√√√ n∑i=1

|ui|2,

where n is its dimension. This can be computed inMatlab in one of two ways:

>> [ sqrt(u*u’), norm(u)]

ans =

19.1050 19.1050

where norm is a built–in Matlab function that accepts avector as input and delivers a scalar as output. It canalso be used to compute other norms: help norm.

Exercise 14.1 The angle, θ, between two column vec-tors x and y is defined by

cos θ =x′y

‖x‖ ‖y‖ .

Use this formula to determine the cosine of the anglebetween

x = [1, 2, 3]′ and y = [3, 2, 1]′.

Hence find the angle in degrees.

14.2 Dot Product (.*)

The second way of forming the product of two vectorsof the same length is known as the Hadamard product.It is not often used in Mathematics but is an invalu-able Matlab feature. It involves vectors of the sametype. If u and v are two vectors of the same type (bothrow vectors or both column vectors), the mathematicaldefinition of this product, which we shall call the dotproduct, is the vector having the components

u · v = [u1v1, u2v2, . . . , unvn].

The result is a vector of the same length and type asu and v. Thus, we simply multiply the correspondingelements of two vectors.In Matlab, the product is computed with the opera-tor .* and, using the vectors u, v, w, z defined onpage 11,

>> u.*w

ans =

20 -11 36

>> u.*v’

ans =

200 231 -264

>> v.*z, u’.*v

ans =

140 -126 -110

ans =

200 231 -264

11

Page 28 of 96

Page 29: Simulink and Exercizes Matlab Coursebook

Example 14.1 Tabulate the function y = x sinπx forx = 0, 0.25, . . . , 1.

It is easier to deal with column vectors so we first definea vector of x-values: (see Transposing: §8.4)>> x = (0:0.25:1)’;

To evaluate y we have to multiply each element of thevector x by the corresponding element of the vectorsinπx:

x × sinπx = x sinπx0 × 0 = 0

0.2500 × 0.7071 = 0.17680.5000 × 1.0000 = 0.50000.7500 × 0.7071 = 0.53031.0000 × 0.0000 = 0.0000

To carry this out in Matlab:

>> y = x.*sin(pi*x)

y =

0

0.1768

0.5000

0.5303

0.0000

Note: a) the use of pi, b) x and sin(pi*x) are bothcolumn vectors (the sin function is applied to each el-ement of the vector). Thus, the dot product of these isalso a column vector.

14.3 Dot Division of Arrays (./)

There is no mathematical definition for the division ofone vector by another. However, in Matlab, the opera-tor ./ is defined to give element by element division—itis therefore only defined for vectors of the same size andtype.

>> a = 1:5, b = 6:10, a./b

a =

1 2 3 4 5

b =

6 7 8 9 10

ans =

0.1667 0.2857 0.3750 0.4444 0.5000

>> a./a

ans =

1 1 1 1 1

>> c = -2:2, a./c

c =

-2 -1 0 1 2

Warning: Divide by zero

ans =

-0.5000 -2.0000 Inf 4.0000 2.5000

The previous calculation required division by 0—noticethe Inf, denoting infinity, in the answer.

>> a.*b -24, ans./c

ans =

-18 -10 0 12 26

Warning: Divide by zero

ans =

9 10 NaN 12 13

Here we are warned about 0/0—giving a NaN (Not aNumber).

Example 14.2 Estimate the limit

limx→0

sinπx

x.

The idea is to observe the behaviour of the ratio sinπxx

for a sequence of values of x that approach zero. Sup-pose that we choose the sequence defined by the columnvector>> x = [0.1; 0.01; 0.001; 0.0001]

then

>> sin(pi*x)./x

ans =

3.0902

3.1411

3.1416

3.1416

which suggests that the values approach π. To get abetter impression, we subtract the value of π from eachentry in the output and, to display more decimal places,we change the format

>> format long

>> ans -pi

ans =

-0.05142270984032

-0.00051674577696

-0.00000516771023

-0.00000005167713

Can you explain the pattern revealed in these numbers?We also need to use ./ to compute a scalar divided bya vector:

>> 1/x

??? Error using ==> /

Matrix dimensions must agree.

>> 1./x

ans =

10 100 1000 10000

so 1./x works, but 1/x does not.

14.4 Dot Power of Arrays (.^)

To square each of the elements of a vector we could, forexample, do u.*u. However, a neater way is to use the.^ operator:

>> u.^2

ans =

100 121 144

>> u.*u

ans =

100 121 144

12

Page 29 of 96

Page 30: Simulink and Exercizes Matlab Coursebook

>> u.^4

ans =

10000 14641 20736

>> v.^2

ans =

400

441

484

>> u.*w.^(-2)

ans =

2.5000 -11.0000 1.3333

Recall that powers (.^ in this case) are done first, beforeany other arithmetic operation.

15 Examples in Plotting

Example 15.1 Draw graphs of the functions

i) y = sin xx

ii) u = 1(x−1)2

+ x

iii) v = x2+1x2−4

iv) w = (10−x)1/3−2

(4−x2)1/2

for 0 ≤ x ≤ 10.

>> x = 0:0.1:10;

>> y = sin(x)./x;

>> subplot(221), plot(x,y), title(’(i)’)

Warning: Divide by zero

>> u = 1./(x-1).^2 + x;

>> subplot(222),plot(x,u), title(’(ii)’)

Warning: Divide by zero

>> v = (x.^2+1)./(x.^2-4);

>> subplot(223),plot(x,v),title(’(iii)’)

Warning: Divide by zero

>> w = ((10-x).^(1/3)-1)./sqrt(4-x.^2);

Warning: Divide by zero

>> subplot(224),plot(x,w),title(’(iv)’)

Note the repeated use of the “dot” operators.Experiment by changing the axes (page 9), grids (page 7)and hold(page 7).

>> subplot(222),axis([0 10 0 10])

>> grid

>> grid

>> hold on

>> plot(x,v,’--’), hold off, plot(x,y,’:’)

Exercise 15.1 Enter the vectors

U = [6, 2, 4], V = [3,−2, 3, 0],

W =

3−4

2−6

, Z =

3227

into Matlab.

1. Which of the products

U*V, V*W, U*V’, V*W’, W*Z’, U.*V

U’*V, V’*W, W’*Z, U.*W, W.*Z, V.*W

is legal? State whether the legal products are rowor column vectors and give the values of the legalresults.

2. Tabulate the functions

y = (x2 + 3) sinπx2

andz = sin2 πx/(x−2 + 3)

for x = 0, 0.2, . . . , 10. Hence, tabulate the func-tion

w =(x2 + 3) sinπx2 sin2 πx

(x−2 + 3).

Plot a graph of w over the range 0 ≤ x ≤ 10.

16 Matrices—Two–DimensionalArrays

Row and Column vectors are special cases of matrices.An m × n matrix is a rectangular array of numbershaving m rows and n columns. It is usual in a math-ematical setting to include the matrix in either roundor square brackets—we shall use square ones. For ex-ample, when m = 2, n = 3 we have a 2× 3 matrix suchas

A =

[5 7 91 −3 −7

]To enter such an matrix into Matlab we type it in rowby row using the same syntax as for vectors:

>> A = [5 7 9

1 -3 -7]

A =

5 7 9

1 -3 -7

Rows may be separated by semi-colons rather than anew line:

>> B = [-1 2 5; 9 0 5]

B =

-1 2 5

9 0 5

>> C = [0, 1; 3, -2; 4, 2]

C =

0 1

3 -2

4 2

13

Page 30 of 96

Page 31: Simulink and Exercizes Matlab Coursebook

>> D = [1:5; 6:10; 11:2:20]

D =

1 2 3 4 5

6 7 8 9 10

11 13 15 17 19

So A and B are 2× 3 matrices, C is 3× 2 and D is 3× 5.In this context, a row vector is a 1 × n matrix and acolumn vector a m× 1 matrix.

16.1 Size of a matrix

We can get the size (dimensions) of a matrix with thecommand size

>> size(A), size(x)

ans =

2 3

ans =

3 1

>> size(ans)

ans =

1 2

So A is 2× 3 and x is 3× 1 (a column vector). The lastcommand size(ans) shows that the value returned bysize is itself a 1×2 matrix (a row vector). We can savethe results for use in subsequent calculations.

>> [r c] = size(A’), S = size(A’)

r =

3

c =

2

S =

3 2

16.2 Transpose of a matrix

Transposing a vector changes it from a row to a columnvector and vice versa (see §8.4). The extension of thisidea to matrices is that transposing interchanges rowswith the corresponding columns: the 1st row becomesthe 1st column, and so on.

>> D, D’

D =

1 2 3 4 5

6 7 8 9 10

11 13 15 17 19

ans =

1 6 11

2 7 13

3 8 15

4 9 17

5 10 19

>> size(D), size(D’)

ans =

3 5

ans =

5 3

16.3 Special Matrices

Matlab provides a number of useful built–in matricesof any desired size.ones(m,n) gives an m× n matrix of 1’s,

>> P = ones(2,3)

P =

1 1 1

1 1 1

zeros(m,n) gives an m× n matrix of 0’s,

>> Z = zeros(2,3), zeros(size(P’))

Z =

0 0 0

0 0 0

ans =

0 0

0 0

0 0

The second command illustrates how we can constructa matrix based on the size of an existing one. Tryones(size(D)).An n×n matrix that has the same number of rows andcolumns and is called a square matrix.A matrix is said to be symmetric if it is equal to itstranspose (i.e. it is unchanged by transposition):

>> S = [2 -1 0; -1 2 -1; 0 -1 2],

S =

2 -1 0

-1 2 -1

0 -1 2

>> St = S’

St =

2 -1 0

-1 2 -1

0 -1 2

>> S-St

ans =

0 0 0

0 0 0

0 0 0

16.4 The Identity Matrix

The n× n identity matrix is a matrix of zeros exceptfor having ones along its leading diagonal (top left tobottom right). This is called eye(n) in Matlab (sincemathematically it is usually denoted by I).

>> I = eye(3), x = [8; -4; 1], I*x

I =

1 0 0

0 1 0

0 0 1

x =

8

-4

1

ans =

8

-4

1

14

Page 31 of 96

Page 32: Simulink and Exercizes Matlab Coursebook

Notice that multiplying the 3× 1 vector x by the 3× 3identity I has no effect (it is like multiplying a numberby 1).

16.5 Diagonal Matrices

A diagonal matrix is similar to the identity matrix ex-cept that its diagonal entries are not necessarily equalto 1.

D =

[ −3 0 00 4 00 0 2

]is a 3×3 diagonal matrix. To construct this in Matlab,we could either type it in directly

>> D = [-3 0 0; 0 4 0; 0 0 2]

D =

-3 0 0

0 4 0

0 0 2

but this becomes impractical when the dimension islarge (e.g. a 100 × 100 diagonal matrix). We then usethe diag function.We first define a vector d, say, con-taining the values of the diagonal entries (in order) thendiag(d) gives the required matrix.

>> d = [-3 4 2], D = diag(d)

d =

-3 4 2

D =

-3 0 0

0 4 0

0 0 2

On the other hand, if A is any matrix, the commanddiag(A) extracts its diagonal entries:

>> F = [0 1 8 7; 3 -2 -4 2; 4 2 1 1]

F =

0 1 8 7

3 -2 -4 2

4 2 1 1

>> diag(F)

ans =

0

-2

1

Notice that the matrix does not have to be square.

16.6 Building Matrices

It is often convenient to build large matrices from smallerones:

>> C=[0 1; 3 -2; 4 2]; x=[8;-4;1];

>> G = [C x]

G =

0 1 8

3 -2 -4

4 2 1

>> A, B, H = [A; B]

A =

5 7 9

1 -3 -7

B =

-1 2 5

9 0 5

ans =

5 7 9

1 -3 -7

-1 2 5

9 0 5

so we have added an extra column (x) to C in order toform G and have stacked A and B on top of each otherto form H.

>> J = [1:4; 5:8; 9:12; 20 0 5 4]

J =

1 2 3 4

5 6 7 8

9 10 11 12

20 0 5 4

>> K = [ diag(1:4) J; J’ zeros(4,4)]

K =

1 0 0 0 1 2 3 4

0 2 0 0 5 6 7 8

0 0 3 0 9 10 11 12

0 0 0 4 20 0 5 4

1 5 9 20 0 0 0 0

2 6 10 0 0 0 0 0

3 7 11 5 0 0 0 0

4 8 12 4 0 0 0 0

The command spy(K) will produce a graphical displayof the location of the nonzero entries in K (it will alsogive a value for nz—the number of nonzero entries):

>> spy(K), grid

16.7 Tabulating Functions

This has been addressed in earlier sections but we arenow in a position to produce a more suitable table for-mat.

Example 16.1 Tabulate the functions y = 4 sin 3x andu = 3 sin 4x for x = 0, 0.1, 0.2, . . . , 0.5.

>> x = 0:0.1:0.5;

>> y = 4*sin(3*x); u = 3*sin(4*x);

>> [ x’ y’ u’]

ans =

0 0 0

0.1000 1.1821 1.1683

0.2000 2.2586 2.1521

0.3000 3.1333 2.7961

0.4000 3.7282 2.9987

0.5000 3.9900 2.7279

Note the use of transpose (’) to get column vectors.(we could replace the last command by [x; y; u;]’)We could also have done this more directly:

>> x = (0:0.1:0.5)’;

>> [x 4*sin(3*x) 3*sin(4*x)]

15

Page 32 of 96

Page 33: Simulink and Exercizes Matlab Coursebook

16.8 Extracting Bits of Matrices

We may extract sections from a matrix in much thesame way as for a vector (page 5).Each element of a matrix is indexed according to whichrow and column it belongs to. The entry in the ith rowand jth column is denoted mathematically by Ai,j and,in Matlab, by A(i,j). So

>> J

J =

1 2 3 4

5 6 7 8

9 10 11 12

20 0 5 4

>> J(1,1)

ans =

1

>> J(2,3)

ans =

7

>> J(4,3)

ans =

5

>> J(4,5)

??? Index exceeds matrix dimensions.

>> J(4,1) = J(1,1) + 6

J =

1 2 3 4

5 6 7 8

9 10 11 12

7 0 5 4

>> J(1,1) = J(1,1) - 3*J(1,2)

J =

-5 2 3 4

5 6 7 8

9 10 11 12

7 0 5 4

In the following examples we extract i) the 3rd column,ii) the 2nd and 3rd columns, iii) the 4th row, and iv)the “central” 2× 2 matrix. See §8.1.

>> J(:,3) % 3rd column

ans =

3

7

11

5

>> J(:,2:3) % columns 2 to 3

ans =

2 3

6 7

10 11

0 5

>> J(4,:) % 4th row

ans =

7 0 5 4

>> J(2:3,2:3) % rows 2 to 3 & cols 2 to 3

ans =

6 7

10 11

Thus, : on its own refers to the entire column or rowdepending on whether it is the first or the second index.

16.9 Dot product of matrices (.*)

The dot product works as for vectors: correspondingelements are multiplied together—so the matrices in-volved must have the same size.

>> A, B

A =

5 7 9

1 -3 -7

B =

-1 2 5

9 0 5

>> A.*B

ans =

-5 14 45

9 0 -35

>> A.*C

??? Error using ==> .*

Matrix dimensions must agree.

>> A.*C’

ans =

0 21 36

1 6 -14

16.10 Matrix–vector products

We turn next to the definition of the product of a matrixwith a vector. This product is only defined for columnvectors that have the same number of entries as thematrix has columns. So, if A is an m× n matrix and xis a column vector of length n, then the matrix–vectorAx is legal.An m × n matrix times an n × 1 matrix ⇒ a m × 1matrix.We visualise A as being made up of m row vectorsstacked on top of each other, then the product cor-responds to taking the scalar product (See §14.1) ofeach row of A with the vector x: The result is a columnvector with m entries.

Ax =

[5 7 9

1 −3 −7

] 8−4

1

=

[5× 8 + 7× (−4) + 9× 1

1× 8 + (−3)× (−4) + (−7)× 1

]=

[2113

]It is somewhat easier in Matlab:

>> A = [5 7 9; 1 -3 -7]

A =

5 7 9

1 -3 -7

>> x = [8; -4; 1]

x =

8

-4

1

>> A*x

ans =

16

Page 33 of 96

Page 34: Simulink and Exercizes Matlab Coursebook

21

13

(m× n) times (n ×1)⇒ (m× 1).

>> x*A

??? Error using ==> *

Inner matrix dimensions must agree.

Unlike multiplication in arithmetic, A*x is not thesame as x*A.

16.11 Matrix–Matrix Products

To form the product of an m×n matrix A and a n× pmatrix B, written as AB, we visualise the first matrix(A) as being composed of m row vectors of length nstacked on top of each other while the second (B) is vi-sualised as being made up of p column vectors of lengthn:

A = m rows

...

, B =

· · ·

︸ ︷︷ ︸p columns

,

The entry in the ith row and jth column of the productis then the scalarproduct of the ith row of A with thejth column of B. The product is an m× p matrix:

(m× n) times (n ×p)⇒ (m× p).

Check that you understand what is meant by workingout the following examples by hand and comparing withthe Matlab answers.

>> A = [5 7 9; 1 -3 -7]

A =

5 7 9

1 -3 -7

>> B = [0, 1; 3, -2; 4, 2]

B =

0 1

3 -2

4 2

>> C = A*B

C =

57 9

-37 -7

>> D = B*A

D =

1 -3 -7

13 27 41

22 22 22

>> E = B’*A’

E =

57 -37

9 -7

We see that E = C’ suggesting that

(A*B)’ = B’*A’Why is B ∗A a 3× 3 matrix while A ∗B is 2× 2?

Exercise 16.1 It is often necessary to factorize a ma-trix, e.g., A = BC or A = STXS where the factors arerequired to have specific properties. Use the ’lookforkeyword’ command to make a list of factorizations com-mands in Matlab.

16.12 Sparse Matrices

Matlab has powerful techniques for handling sparse ma-trices — these are generally large matrices (to make theextra work involved worthwhile) that have only a verysmall proportion of non–zero entries.

Example 16.2 Create a sparse 5× 4 matrix S havingonly 3 non–zero values: S1,2 = 10, S3,3 = 11 and S5,4 =12.

We first create 3 vectors containing the i–index, the j–index and the corresponding values of each term andwe then use the sparse command.

>> i = [1, 3, 5]; j = [2,3,4];

>> v = [10 11 12];

>> S = sparse (i,j,v)

S =

(1,2) 10

(3,3) 11

(5,4) 12

>> T = full(S)

T =

0 10 0 0

0 0 0 0

0 0 11 0

0 0 0 0

0 0 0 12

The matrix T is a “full” version of the sparse matrix S.

Example 16.3 Develop Matlab code to create, for anygiven value of n, the sparse (tridiagonal) matrix

B =

1 n−2 2 n− 1

−3 3 n− 2

. . .. . .

. . .

−n+ 1 n− 1 1−n n

We define three column vectors, one for each “diago-nal” of non–zeros and then assemble the matrix usingspdiags (short for sparse diagonals). The vectors arenamed l, d and u. They must all have the same lengthand only the first n − 1 terms of l are used while thelast n − 1 terms of u are used. spdiags places thesevectors in the diagonals labelled -1, 0 and 1 (0 defersto the leading diagonal, negatively numbered diagonalslie below the leading diagonal, etc.)

>> n = 5;

>> l = -(2:n+1)’; d = (1:n )’; u = ((n+1):-1:2)’;

>> B = spdiags([l’ d’ u’],-1:1,n,n);

>> full(B)

ans =

17

Page 34 of 96

Page 35: Simulink and Exercizes Matlab Coursebook

1 5 0 0 0

-2 2 4 0 0

0 -3 3 3 0

0 0 -4 4 2

0 0 0 -5 5

17 Systems of Linear Equations

Mathematical formulations of engineering problems of-ten lead to sets of simultaneous linear equations. Suchis the case, for instance, when using the finite elementmethod (FEM).A general system of linear equations can be expressedin terms of a coefficient matrix A, a right-hand-side(column) vector b and an unknown (column) vector xas

Ax = b

or, componentwise, as

a1,1x1 + a1,2x2 + · · · a1,nxn = b1

a2,1x1 + a2,2x2 + · · · a2,nxn = b2

...

an,1x1 + an,2x2 + · · · an,nxn = bn

When A is non-singular and square (n × n), meaningthat the number of independent equations is equal tothe number of unknowns, the system has a unique so-lution given by

x = A−1b

where A−1 is the inverse of A. Thus, the solution vectorx can, in principle, be calculated by taking the inverseof the coefficient matrix A and multiplying it on theright with the right-hand-side vector b.This approach based on the matrix inverse, though for-mally correct, is at best inefficient for practical applica-tions (where the number of equations may be extremelylarge) but may also give rise to large numerical errorsunless appropriate techniques are used. These issues arediscussed in most courses and texts on numerical meth-ods. Various stable and efficient solution techniqueshave been developed for solving linear equations andthe most appropriate in any situation will depend onthe properties of the coefficient matrix A. For instance,on whether or not it is symmetric, or positive definite orif it has a particular structure (sparse or full). Matlabis equipped with many of these special techniques in itsroutine library and they are invoked automatically.The standard Matlab routine for solving systems oflinear equations is invoked by calling the matrix left-division routine,

>> x = A \ b

where “\” is the matrix left-division operator known as“backslash” (see help backslash).

Exercise 17.1 Enter the symmetric coefficient matrixand right–hand–side vector b given by

A =

[2 −1 01 −2 10 −1 2

], b =

[101

]

and solve the system of equations Ax = b using thethree alternative methods:

i) x = A−1b, (the inverse A−1 may be computed inMatlab using inv(A).)

ii) x = A \ b,

iii) xT = btAT leading to xT = b’ / A which makesuse of the “slash” or “right division” operator“/”. The required solution is then the transposeof the row vector xT.

Exercise 17.2 Use the backslash operator to solve thecomplex system of equations for which

A =

[2 + 2i −1 0−1 2− 2i −10 −1 2

], b =

[1 + i

01− i

]

Exercise 17.3 Find information on the matrix inver-sion command ’inv’ using each of the methods listed inSection 2 for obtaining help.What kind of matrices are the ’inv’ command applicableto?Obviously problems may occur if the inverted matrix isnearly singular. Suggest a command that can be usedto give an indication on whether the matrix is nearlysingular or not. [Hint: see the topics referred to by’help inv’.]

17.1 Overdetermined system of lin-ear equations

An overdetermined system of linear equations is a onewith more equations (m) than unknowns (n), i.e., thecoefficient matrix has more rows than columns (m > n).Overdetermined systems frequently appear in mathe-matical modelling when the parameters of a model aredetermined by fitting to experimental data. Formallythe system looks the same as for square systems but thecoefficient matrix is rectangular and so it is not possibleto compute an inverse. In these cases a solution can befound by requiring that the magnitude of the residualvector r, defined by

r = Ax− b,

be minimized. The simplest and most frequently usedmeasure of the magnitude of r is require the Euclideanlength (or norm—see Section 14.1) which correspondsto the sum of squares of the components of the resid-ual. This approach leads to the least squares solutionof the overdetermined system. Hence the least squaressolution is defined as the vector x that minimizes

rT r.

It may be shown that the required solution satisfies theso–called “normal equations”

Cx = d, where C = ATA and d = ATb.

This system is well–known that the solution of this sys-tem can be overwhelmed by numerical rounding errorin practice unless great care is taken in its solution (a

18

Page 35 of 96

Page 36: Simulink and Exercizes Matlab Coursebook

large part of the difficulty is inherent in computing thematrix–matrix product ATA). As in the solution ofsquare systems of linear equations, special techniqueshave been developed to address these issues and theyhave been incorporated into the Matlab routine library.This means that a direct solution to the problem ofoverdetermined equations is available in Matlab throughits left division operator “\”. When the matrix A is notsquare, the operation

x = A\b

automatically gives the least squares solution to Ax =b. This is illustrated in the next example.

Example 17.1 A spring is a mechanical element which,for the simplest model, is characterized by a linear force-deformation relationship

F = kx,

F being the force loading the spring, k the spring con-stant or stiffness and x the spring deformation. In re-ality the linear force–deformation relationship is onlyan approximation, valid for small forces and deforma-tions. A more accurate relationship, valid for largerdeformations, is obtained if non–linear terms are takeninto account. Suppose a spring model with a quadraticrelationship

F = k1x+ k2x2

is to be used and that the model parameters, k1 andk2, are to be determined from experimental data. Fiveindependent measurements of the force and the corre-sponding spring deformations are measured and theseare presented in Table 1.

Force F [N] Deformation x [cm]5 0.001

50 0.011500 0.013

1000 0.302000 0.75

Table 1: Measured force-deformation data forspring.

Using the quadratic force-deformation relationship to-gether with the experimental data yields an overdeter-mined system of linear equations and the componentsof the residual are given by

r1 = x1k1 + x21k2 − F1

r2 = x2k1 + x22k2 − F2

r3 = x3k1 + x23k2 − F3

r4 = x4k1 + x24k2 − F4

r5 = x5k1 + x25k2 − F5.

These lead to the matrix and vector definitions

A =

x1 x2

1

x2 x22

x3 x23

x4 x24

x5 x25

and b =

F1

F2

F3

F4

F5.

The appropriate Matlab commands give (the compo-nents of x are all multiplied by 1e-2, i.e., 10−2, in orderto change from cm to m)

>> x = [.001 .011 .13 .3 .75]*1e-2;

>> A = [x’ (x’).^2]

A =

0.0000 0.0000

0.0001 0.0000

0.0013 0.0000

0.0030 0.0000

0.0075 0.0001

>> b = [5 50 500 1000 2000];

and the least squares solution to this system is given by

>> k = A\b’

k =

1.0e+07 *

0.0386

-1.5993

Thus, k ≈[

0.39−16.0

]× 106 and the quadratic spring

force-deformation relationship that optimally fits ex-perimental data in the least squares sense is

F ≈ 38.6× 104x− 16.0× 106x2.

The data and solution may be plotted with the follow-ing commands

>> plot(x,f,’o’), hold on % plot data points

>> X = (0:.01:1)*max(x);

>> plot(X,[X’ (X.^2)’]*k,’-’) % best fit curve

>> xlabel(’x[m]’), ylabel(’F[N]’)

and the results are shown in Figure 5.

Figure 5: Data for Example 17.1 (circles) and bestleast squares fit by a quadratic model (solid line).

Matlab has a routine polyfit for data fitting by poly-nomials: see “help polyfit”. It is not applicable inthis example because we require that the force – de-formation law passes through the origin (so there is noconstant term in the quadratic model that we used).

19

Page 36 of 96

Page 37: Simulink and Exercizes Matlab Coursebook

18 Characters, Strings and Text

The ability to process text in numerical processing isuseful for the input and output of data to the screen orto disk-files. In order to manage text, a new datatypeof “character” is introduced. A piece of text is thensimply a string (vector) or array of characters.

Example 18.1 The assignment,

>> t1 = ’A’

assigns the value A to the 1-by-1 character array t1.The assignment,

>> t2 = ’BCDE’

assigns the value BCDE to the 1-by-4 character arrayt2.

Strings can be combined by using the operations forarray manipulations.The assignment,

>> t3 = [t1,t2]

assigns a value ABCDE to the 1-by-5 character array t3.The assignment,

>> t4 = [t3,’ are the first 5 ’;...

’characters in the alphabet.’]

assigns the value’ABCDE are the first 5 ’

’characters in the alphabet.’

to the 2-by-27 character array t4. It is essential thatthe number of characters in both rows of the array t4

is the same, otherwise an error will result. The threedots ... signify that the command is continued on thefollowing lineSometimes it is necessary to convert a character to thecorresponding number, or vice versa. These conversionsare accomplished by the commands ’str2num’—whichconverts a string to the corresponding number, and twofunctions, ’int2str’ and ’num2str’, which convert, re-spectively, an integer and a real number to the corre-sponding character string. These commands are usefulfor producing titles and strings, such as ’The value of

pi is 3.1416’. This can be generated by the command[’The value of pi is ’,num2str(pi)].

>> N = 5; h = 1/N;

>> [’The value of N is ’,int2str(N),...

’, h = ’,num2str(h)]

ans =

The value of N is 5, h = 0.2

19 Loops

There are occasions that we want to repeat a segment ofcode a number of different times (such occasions are lessfrequent than other programming languages because ofthe : notation).

Example 19.1 Draw graphs of sin(nπx) on the inter-val −1 ≤ x ≤ 1 for n = 1, 2, . . . , 8.

We could do this by giving 8 separate plot commandsbut it is much easier to use a loop. The simplest formwould be

>> x = -1:.05:1;

>> for n = 1:8

subplot(4,2,n), plot(x,sin(n*pi*x))

end

All the commands between the lines starting “for” and“end” are repeated with n being given the value 1 thefirst time through, 2 the second time, and so forth,until n = 8. The subplot constructs a 4 × 2 array ofsubwindows and, on the nth time through the loop, apicture is drawn in the nth subwindow.

20

Page 37 of 96

Page 38: Simulink and Exercizes Matlab Coursebook

The commands

>> x = -1:.05:1;

>> for n = 1:2:8

subplot(4,2,n), plot(x,sin(n*pi*x))

subplot(4,2,n+1), plot(x,cos(n*pi*x))

end

draw sinnπx and cosnπx for n = 1, 3, 5, 7 alongsideeach other.We may use any legal variable name as the “loop counter”(n in the above examples) and it can be made to runthrough all of the values in a given vector (1:8 and1:2:8 in the examples).We may also use for loops of the type

>> for counter = [23 11 19 5.4 6]

.......

end

which repeats the code as far as the end withcounter=23 the first time, counter=11 the second time,and so forth.

Example 19.2 The Fibonnaci sequence starts off withthe numbers 0 and 1, then succeeding terms are thesum of its two immediate predecessors. Mathematically,f1 = 0, f2 = 1 and

fn = fn−1 + fn−2, n = 3, 4, 5, . . . .

Test the assertion that the ratio fn−1/fn of two suc-cessive values approaches the golden ratio (

√5− 1)/2

= 0.6180 . . ..

>> F(1) = 0; F(2) = 1;

>> for i = 3:20

F(i) = F(i-1) + F(i-2);

end

>> plot(1:19, F(1:19)./F(2:20),’o’ )

>> hold on, xlabel(’n’)

>> plot(1:19, F(1:19)./F(2:20),’-’ )

>> legend(’Ratio of terms f_n-1/f_n’)

>> plot([0 20], (sqrt(5)-1)/2*[1,1],’--’)

The last of these commands produces the dashed hori-zontal line.

Example 19.3 Produce a list of the values of the sums

S20 = 1 + 122 + 1

32 + · · ·+ 1202

S21 = 1 + 122 + 1

32 + · · ·+ 1202 + 1

212

...S100 = 1 + 1

22 + 132 + · · ·+ 1

202 + 1212 + · · ·+ 1

1002

There are a total of 81 sums. The first can be computedusing sum(1./(1:20).^2) (The function sum with a vec-tor argument sums its components. See §22.2].) A suit-able piece of Matlab code might be

>> S = zeros(100,1);

>> S(20) = sum(1./(1:20).^2);

>> for n = 21:100

>> S(n) = S(n-1) + 1/n^2;

>> end

>> clf; plot(S,’.’,[20 100],[1,1]*pi^2/6,’-’)

>> axis([20 100 1.5 1.7])

>> [ (98:100)’ S(98:100)]

ans =

98.0000 1.6364

99.0000 1.6365

100.0000 1.6366

where a column vector S was created to hold the an-swers. The first sum was computed directly using thesum command then each succeeding sum was found byadding 1/n2 to its predecessor. The little table at theend shows the values of the last three sums—it appearsthat they are approaching a limit (the value of the limitis π2/6 = 1.64493 . . .).

Exercise 19.1 Repeat Example 19.3 to include 181sums (i.e., the final sum should include the term 1/2002.)

20 Logicals

Matlab represents true and false by means of the in-tegers 0 and 1.

true = 1, false = 0

If at some point in a calculation a scalar x, say, has beenassigned a value, we may make certain logical tests onit:x == 2 is x equal to 2?x ~= 2 is x not equal to 2?x > 2 is x greater than 2?x < 2 is x less than 2?x >= 2 is x greater than or equal to 2?x <= 2 is x less than or equal to 2?

Pay particular attention to the fact that the test forequality involves two equal signs ==.

>> x = pi

x =

3.1416

>> x ~= 3, x ~= pi

ans =

1

ans =

0

21

Page 38 of 96

Page 39: Simulink and Exercizes Matlab Coursebook

When x is a vector or a matrix, these tests are per-formed elementwise:

x =

-2.0000 3.1416 5.0000

-1.0000 0 1.0000

>> x == 0

ans =

0 0 0

0 1 0

>> x > 1, x >=-1

ans =

0 1 1

0 0 0

ans =

0 1 1

1 1 1

>> y = x>=-1, x > y

y =

0 1 1

1 1 1

ans =

0 1 1

0 0 0

We may combine logical tests, as in

>> x

x =

-2.0000 3.1416 5.0000

-5.0000 -3.0000 -1.0000

>> x > 3 & x < 4

ans =

0 1 0

0 0 0

>> x > 3 | x == -3

ans =

0 1 1

0 1 0

As one might expect, & represents and and (not soclearly) the vertical bar | means or; also ~ means notas in ~= (not equal), ~(x>0), etc.

>> x > 3 | x == -3 | x <= -5

ans =

0 1 1

1 1 0

One of the uses of logical tests is to “mask out” certainelements of a matrix.

>> x, L = x >= 0

x =

-2.0000 3.1416 5.0000

-5.0000 -3.0000 -1.0000

L =

0 1 1

0 1 1

>> pos = x.*L

pos =

0 3.1416 5.0000

0 0 0

so the matrix pos contains just those elements of x thatare non–negative.

>> x = 0:0.05:6; y = sin(pi*x); Y = (y>=0).*y;

>> plot(x,y,’:’,x,Y,’-’ )

20.1 While Loops

There are some occasions when we want to repeat asection of Matlab code until some logical condition issatisfied, but we cannot tell in advance how many timeswe have to go around the loop. This we can do with awhile...end construct.

Example 20.1 What is the greatest value of n that canbe used in the sum

12 + 22 + · · ·+ n2

and get a value of less than 100?

>> S = 1; n = 1;

>> while S+ (n+1)^2 < 100

n = n+1; S = S + n^2;

end

>> [n, S]

ans =

6 91

The lines of code between while and end will only beexecuted if the condition S+ (n+1)^2 < 100 is true.

Exercise 20.1 Replace 100 in the previous example by10 and work through the lines of code by hand. Youshould get the answers n = 2 and S = 5.

Exercise 20.2 Type the code from Example20.1 into ascript–file named WhileSum.m (See §13.)

A more typical example is

Example 20.2 Find the approximate value of the rootof the equation x = cosx. (See Example 10.1.)

We may do this by making a guess x1 = π/4, say, thencomputing the sequence of values

xn = cosxn−1, n = 2, 3, 4, . . .

and continuing until the difference between two succes-sive values |xn − xn−1| is small enough.

22

Page 39 of 96

Page 40: Simulink and Exercizes Matlab Coursebook

Method 1:

>> x = zeros(1,20); x(1) = pi/4;

>> n = 1; d = 1;

>> while d > 0.001

n = n+1; x(n) = cos(x(n-1));

d = abs( x(n) - x(n-1) );

end

n,x

n =

14

x =

Columns 1 through 7

0.7854 0.7071 0.7602 0.7247 0.7487 0.7326 0.7435

Columns 8 through 14

0.7361 0.7411 0.7377 0.7400 0.7385 0.7395 0.7388

Columns 15 through 20

0 0 0 0 0 0

There are a number of deficiencies with this program.The vector x stores the results of each iteration but wedon’t know in advance how many there may be. Inany event, we are rarely interested in the intermediatevalues of x, only the last one. Another problem is thatwe may never satisfy the condition d ≤ 0.001, in whichcase the program will run forever—we should place alimit on the maximum number of iterations.Incorporating these improvements leads to

Method 2:

>> xold = pi/4; n = 1; d = 1;

>> while d > 0.001 & n < 20

n = n+1; xnew = cos(xold);

d = abs( xnew - xold );

xold = xnew;

end

>> [n, xnew, d]

ans =

14.0000 0.7388 0.0007

We continue around the loop so long as d > 0.001 andn < 20. For greater precision we could use the conditiond > 0.0001, and this gives

>> [n, xnew, d]

ans =

19.0000 0.7391 0.0001

from which we may judge that the root required is x =0.739 to 3 decimal places.The general form of while statement is

while a logical testCommands to be executedwhen the condition is true

end

20.2 if...then...else...end

This allows us to execute different commands depend-ing on the truth or falsity of some logical tests. To testwhether or not πe is greater than, or equal to, eπ:

>> a = pi^exp(1); c = exp(pi);

>> if a >= c

b = sqrt(a^2 - c^2)

end

so that b is assigned a value only if a ≥ c. There is nooutput so we deduce that a = πe < c = eπ. A morecommon situation is

>> if a >= c

b = sqrt(a^2 - c^2)

else

b = 0

end

b =

0

which ensures that b is always assigned a value andconfirming that a < c.A more extended form is

>> if a >= c

b = sqrt(a^2 - c^2)

elseif a^c > c^a

b = c^a/a^c

else

b = a^c/c^a

end

b =

0.2347

Exercise 20.3 Which of the above statements assigneda value to b?

The general form of the if statement is

if logical test 1Commands to be executed if test 1 istrue

elseif logical test 2Commands to be executed if test 2 istrue but test 1 is false...

end

21 Function m–files

These are a combination of the ideas of script m–files(§7) and mathematical functions.

Example 21.1 The area, A, of a triangle with sidesof length a, b and c is given by

A =√s(s− a)(s− b)(s− c),

where s = (a + b + c)/2. Write a Matlab function thatwill accept the values a, b and c as inputs and returnthe value of A as output.

The main steps to follow when defining a Matlab func-tion are:

23

Page 40 of 96

Page 41: Simulink and Exercizes Matlab Coursebook

1. Decide on a name for the function, making surethat it does not conflict with a name that is al-ready used by Matlab. In this example the nameof the function is to be area, so its definition willbe saved in a file called area.m

2. The first line of the file must have the format:

function [list of outputs]

= function name(list of inputs)

For our example, the output (A) is a function ofthe three variables (inputs) a, b and c so the firstline should read

function [A] = area(a,b,c)

3. Document the function. That is, describe brieflythe purpose of the function and how it can beused. These lines should be preceded by % whichsignify that they are comment lines that will beignored when the function is evaluated.

4. Finally include the code that defines the func-tion. This should be interspersed with sufficientcomments to enable another user to understandthe processes involved.

The complete file might look like:

function [A] = area(a,b,c)

% Compute the area of a triangle whose

% sides have length a, b and c.

% Inputs:

% a,b,c: Lengths of sides

% Output:

% A: area of triangle

% Usage:

% Area = area(2,3,4);

% Written by dfg, Oct 14, 1996.

s = (a+b+c)/2;

A = sqrt(s*(s-a)*(s-b)*(s-c));

%%%%%%%%% end of area %%%%%%%%%%%

The command>> help area

will produce the leading comments from the file:

Compute the area of a triangle whose

sides have length a, b and c.

Inputs:

a,b,c: Lengths of sides

Output:

A: area of triangle

Usage:

Area = area(2,3,4);

Written by dfg, Oct 14, 1996.

To evaluate the area of a triangle with side of length10, 15, 20:

>> Area = area(10,15,20)

Area =

72.6184

where the result of the computation is assigned to thevariable Area. The variable s used in the definition ofthe function above is a “local variable”: its value is localto the function and cannot be used outside:

>> s

??? Undefined function or variable s.

If we were to be interested in the value of s as well asA, then the first line of the file should be changed to

function [A,s] = area(a,b,c)

where there are two output variables.This function can be called in several different ways:

1. No outputs assigned

>> area(10,15,20)

ans =

72.6184

gives only the area (first of the output variablesfrom the file) assigned to ans; the second outputis ignored.

2. One output assigned

>> Area = area(10,15,20)

Area =

72.6184

again the second output is ignored.

3. Two outputs assigned

>> [Area, hlen] = area(10,15,20)

Area =

72.6184

hlen =

22.5000

Exercise 21.1 In any triangle the sum of the lengthsof any two sides cannot exceed the length of the thirdside. The function area does not check to see if thiscondition is fulfilled (try area(1,2,4)). Modify the fileso that it computes the area only if the sides satisfy thiscondition.

21.1 Examples of functions

We revisit the problem of computing the Fibonnaci se-quence defined by f1 = 0, f2 = 1 and

fn = fn−1 + fn−2, n = 3, 4, 5, . . . .

We want to construct a function that will return thenth number in the Fibonnaci sequence fn.

• Input: Integer n

• Output: fn

We shall describe four possible functions and try to as-sess which provides the best solution.

Method 1: File Fib1.m

function f = Fib1(n)

% Returns the nth number in the

% Fibonacci sequence.

F=zeros(1,n+1);

F(2) = 1;

for i = 3:n+1

F(i) = F(i-1) + F(i-2);

end

f = F(n);

24

Page 41 of 96

Page 42: Simulink and Exercizes Matlab Coursebook

This code resembles that given in Example 19.2. Wehave simply enclosed it in a function m–file and givenit the appropriate header,

Method 2: File Fib2.m

The first version was rather wasteful of memory—itsaved all the entries in the sequence even though weonly required the last one for output. The second ver-sion removes the need to use a vector.

function f = Fib2(n)

% Returns the nth number in the

% Fibonacci sequence.

if n==1

f = 0;

elseif n==2

f = 1;

else

f1 = 0; f2 = 1;

for i = 2:n-1

f = f1 + f2;

f1=f2; f2 = f;

end

end

Method 3: File: Fib3.m

This version makes use of an idea called “recursiveprogramming”— the function makes calls to itself.

function f = Fib3(n)

% Returns the nth number in the

% Fibonacci sequence.

if n==1

f = 0;

elseif n==2

f = 1;

else

f = Fib3(n-1) + Fib3(n-2);

end

Method 4: File Fib4.m

The final version uses matrix powers. The vector y has

two components, y =

[fnfn+1

].

function f = Fib4(n)

% Returns the nth number in the

% Fibonacci sequence.

A = [0 1;1 1];

y = A^n*[1;0];

f=y(1);

Assessment: One may think that, on grounds ofstyle, the 3rd is best (it avoids the use of loops) fol-lowed by the second (it avoids the use of a vector). Thesituation is much different when it cames to speed ofexecution. When n = 20 the time taken by each of themethods is (in seconds)

Method Time

1 0.01182 0.01573 36.59374 0.0078

It is impractical to use Method 3 for any value of nmuch larger than 10 since the time taken by method 3almost doubles whenever n is increased by just 1. Whenn = 150

Method Time

1 0.05402 0.08913 —4 0.0106

Clearly the 4th method is much the fastest.

22 Further Built–in Functions

22.1 Rounding Numbers

There are a variety of ways of rounding and choppingreal numbers to give integers. Use the definitions givenin the table in §28 on page 32 in order to understandthe output given below:

>> x = pi*(-1:3), round(x)

x =

-3.1416 0 3.1416 6.2832 9.4248

ans =

-3 0 3 6 9

>> fix(x)

ans =

-3 0 3 6 9

>> floor(x)

ans =

-4 0 3 6 9

>> ceil(x)

ans =

-3 0 4 7 10

>> sign(x), rem(x,3)

ans =

-1 0 1 1 1

ans =

-0.1416 0 0.1416 0.2832 0.4248

Do “help round” for help information.

22.2 The sum Function

The “sum” applied to a vector adds up its components(as in sum(1:10)) while, for a matrix, it adds up thecomponents in each column and returns a row vector.sum(sum(A)) then sums all the entries of A.

>> A = [1:3; 4:6; 7:9]

A =

1 2 3

4 5 6

7 8 9

>> s = sum(A), ss = sum(sum(A))

25

Page 42 of 96

Page 43: Simulink and Exercizes Matlab Coursebook

s =

12 15 18

ss =

45

>> x = pi/4*(1:3)’;

>> A = [sin(x), sin(2*x), sin(3*x)]/sqrt(2)

>> A =

0.5000 0.7071 0.5000

0.7071 0.0000 -0.7071

0.5000 -0.7071 0.5000

>> s1 = sum(A.^2), s2 = sum(sum(A.^2))

s1 =

1.0000 1.0000 1.0000

s2 =

3.0000

The sums of squares of the entries in each column of A

are equal to 1 and the sum of squares of all the entriesis equal to 3.

>> A*A’

ans =

1.0000 0 0

0 1.0000 0.0000

0 0.0000 1.0000

>> A’*A

ans =

1.0000 0 0

0 1.0000 0.0000

0 0.0000 1.0000

It appears that the products AA′ and A′A are bothequal to the identity:

>> A*A’ - eye(3)

ans =

1.0e-15 *

-0.2220 0 0

0 -0.2220 0.0555

0 0.0555 -0.2220

>> A’*A - eye(3)

ans =

1.0e-15 *

-0.2220 0 0

0 -0.2220 0.0555

0 0.0555 -0.2220

This is confirmed since the differences are at round–off error levels (less than 10−15). A matrix with thisproperty is called an orthogonal matrix.

22.3 max & min

These functions act in a similar way to sum. If x is avector, then max(x) returns the largest element in x

>> x = [1.3 -2.4 0 2.3], max(x), max(abs(x))

x =

1.3000 -2.4000 0 2.3000

ans =

2.3000

ans =

2.4000

>> [m, j] = max(x)

m =

2.3000

j =

4

When we ask for two outputs, the first gives us the max-imum entry and the second the index of the maximumelement.For a matrix, A, max(A) returns a row vector containingthe maximum element from each column. Thus to findthe largest element in A we have to use max(max(A)).

22.4 Random Numbers

The function rand(m,n) produces an m × n matrix ofrandom numbers, each of which is in the range 0 to 1.rand on its own produces a single random number.

>> y = rand, Y = rand(2,3)

y =

0.9191

Y =

0.6262 0.1575 0.2520

0.7446 0.7764 0.6121

Repeating these commands will lead to different an-swers.Example: Write a function–file that will simulate nthrows of a pair of dice.This requires random numbers that are integers in therange 1 to 6. Multiplying each random number by 6will give a real number in the range 0 to 6; roundingthese to whole numbers will not be correct since it willthen be possible to get 0 as an answer. We need to use

floor(1 + 6*rand)

Recall that floor takes the largest integer that is smallerthan a given real number (see Table 2, page 32).File: dice.m

function [d] = dice(n)

% simulates "n" throws of a pair of dice

% Input: n, the number of throws

% Output: an n times 2 matrix, each row

% referring to one throw.

%

% Useage: T = dice(3)

d = floor(1 + 6*rand(n,2));

%% end of dice

>> dice(3)

ans =

6 1

2 3

4 1

>> sum(dice(100))/100

ans =

3.8500 3.4300

The last command gives the average value over 100throws (it should have the value 3.5).

26

Page 43 of 96

Page 44: Simulink and Exercizes Matlab Coursebook

22.5 find for vectors

The function “find” returns a list of the positions (in-dices) of the elements of a vector satisfying a given con-dition. For example,

>> x = -1:.05:1;

>> y = sin(3*pi*x).*exp(-x.^2); plot(x,y,’:’)

>> k = find(y > 0.2)

k =

Columns 1 through 12

9 10 11 12 13 22 23 24 25 26 27 36

Columns 13 through 15

37 38 39

>> hold on, plot(x(k),y(k),’o’)

>> km = find( x>0.5 & y<0)

km =

32 33 34

>> plot(x(km),y(km),’-’)

22.6 find for matrices

The find–function operates in much the same way formatrices:

>> A = [ -2 3 4 4; 0 5 -1 6; 6 8 0 1]

A =

-2 3 4 4

0 5 -1 6

6 8 0 1

>> k = find(A==0)

k =

2

9

Thus, we find that A has elements equal to 0 in positions2 and 9. To interpret this result we have to recognizethat “find” first reshapes A into a column vector—thisis equivalent to numbering the elements of A by columnsas in

1 4 7 102 5 8 113 6 9 12

>> n = find(A <= 0)

n =

1

2

8

9

>> A(n)

ans =

-2

0

-1

0

Thus, n gives a list of the locations of the entries in A

that are ≤ 0 and then A(n) gives us the values of theelements selected.

>> m = find( A’ == 0)

m =

5

11

Since we are dealing with A’, the entries are numberedby rows.

23 Plotting Surfaces

A surface is defined mathematically by a function f(x, y)—corresponding to each value of (x, y) we compute theheight of the function by

z = f(x, y).

In order to plot this we have to decide on the rangesof x and y—suppose 2 ≤ x ≤ 4 and 1 ≤ y ≤ 3. Thisgives us a square in the (x, y)–plane. Next, we need tochoose a grid on this domain; Figure 6 shows the gridwith intervals 0.5 in each direction. Finally, we have

Figure 6: An example of a 2D grid

to evaluate the function at each point of the grid and“plot” it.Suppose we choose a grid with intervals 0.5 in eachdirection for illustration. The x– and y–coordinates ofthe grid lines are

x = 2:0.5:4; y = 1:0.5:3;

in Matlab notation. We construct the grid with meshgrid:

27

Page 44 of 96

Page 45: Simulink and Exercizes Matlab Coursebook

>> [X,Y] = meshgrid(2:.5:4, 1:.5:3);

>> X

X =

2.0000 2.5000 3.0000 3.5000 4.0000

2.0000 2.5000 3.0000 3.5000 4.0000

2.0000 2.5000 3.0000 3.5000 4.0000

2.0000 2.5000 3.0000 3.5000 4.0000

2.0000 2.5000 3.0000 3.5000 4.0000

>> Y

Y =

1.0000 1.0000 1.0000 1.0000 1.0000

1.5000 1.5000 1.5000 1.5000 1.5000

2.0000 2.0000 2.0000 2.0000 2.0000

2.5000 2.5000 2.5000 2.5000 2.5000

3.0000 3.0000 3.0000 3.0000 3.0000

If we think of the ith point along from the left andthe jth point up from the bottom of the grid) as corre-sponding to the (i, j)th entry in a matrix, then (X(i,j),

Y(i,j)) are the coordinates of the point. We then needto evaluate the function f using X and Y in place of xand y, respectively.

Example 23.1 Plot the surface defined by the function

f(x, y) = (x− 3)2 − (y − 2)2

for 2 ≤ x ≤ 4 and 1 ≤ y ≤ 3.

>> [X,Y] = meshgrid(2:.2:4, 1:.2:3);

>> Z = (X-3).^2-(Y-2).^2;

>> mesh(X,Y,Z)

>> title(’Saddle’), xlabel(’x’),ylabel(’y’)

Figure 7: Plot of Saddle function.

Exercise 23.1 Repeat the previous example replacingmesh by surf and then by surfl. Consult the help pagesto find out more about these functions.

Example 23.2 Plot the surface defined by the function

f = −xye−2(x2+y2)

on the domain −2 ≤ x ≤ 2,−2 ≤ y ≤ 2. Find thevalues and locations of the maxima and minima of thefunction.

>> [X,Y] = meshgrid(-2:.1:2,-2:.2:2);

>> f = -X.*Y.*exp(-2*(X.^2+Y.^2));

>> figure (1)

>> mesh(X,Y,f), xlabel(’x’), ylabel(’y’), grid

>> figure (2), contour(X,Y,f)

>> xlabel(’x’), ylabel(’y’), grid, hold on

Figure 8: “mesh” and “contour” plots.

To locate the maxima of the “f” values on the grid:

>> fmax = max(max(f))

fmax =

0.0886

>> kmax = find(f==fmax)

kmax =

323

539

>> Pos = [X(kmax), Y(kmax)]

Pos =

-0.5000 0.6000

0.5000 -0.6000

>> plot(X(kmax),Y(kmax),’*’)

>> text(X(kmax),Y(kmax),’ Maximum’)

24 Timing

Matlab allows the timing of sections of code by pro-viding the functions tic and toc. tic switches on astopwatch while toc stops it and returns the CPU time

28

Page 45 of 96

Page 46: Simulink and Exercizes Matlab Coursebook

Figure 9: contour plot showing maxima.

(Central Processor Unit) in seconds. The timings willvary depending on the model of computer being usedand its current load.

>> tic,for j=1:1000,x = pi*R(3);end,toc

elapsed_time = 0.5110

>> tic,for j=1:1000,x=pi*R(3);end,toc

elapsed_time = 0.5017

>> tic,for j=1:1000,x=R(3)/pi;end,toc

elapsed_time = 0.5203

>> tic,for j=1:1000,x=pi+R(3);end,toc

elapsed_time = 0.5221

>> tic,for j=1:1000,x=pi-R(3);end,toc

elapsed_time = 0.5154

>> tic,for j=1:1000,x=pi^R(3);end,toc

elapsed_time = 0.6236

25 On–line Documentation

In addition to the on–line help facility, there is a hy-pertext browsing system giving details of (most) com-mands and some examples. This is accessed by

>> doc

which brings up the Netscape document previewer (andallows for “surfing the internet superhighway”—the WorldWide Web (WWW). It is connected to a worldwide sys-tem which, given the appropriate addresses, will pro-vide information on almost any topic).Words that are underlined in the browser may be clickedon with LB and lead to either a further subindex or ahelp page.Scroll down the page shown and click on general whichwill take you to “General Purpose Commands”; click onclear. This will describe how you can clear a variable’svalue from memory.You may then either click the “Table of Contents” which

takes you back to the start, “Index” or the Back but-ton at the lower left corner of the window which willtake you back to the previous screen.

To access other “home pages”, click on Open at the

bottom of the window and, in the “box” that will openup, type

http://www.maths.dundee.ac.uk

or

http://www.maths.dundee.ac.uk/software/

and select Matlab from the array of choices.

26 Reading and Writing DataFiles

Direct input of data from keyboard becomes impracti-cal when

• the amount of data is large and

• the same data is analysed repeatedly.

In these situations input and output is preferably ac-complished via data files. We have already described inSection 9 the use of the commands save and load that,respectively, write and read the values of variables todisk files.When data are written to or read from a file it is cru-cially important that a correct data format is used. Thedata format is the key to interpreting the contents of afile and must be known in order to correctly interpretthe data in an input file. There a two types of datafiles: formatted and unformatted. Formatted data filesuses format strings to define exactly how and in whatpositions of a record the data is stored. Unformattedstorage, on the other hand, only specifies the numberformat.The files used in this section are available from the website

http://www.maths.dundee.ac.uk/software/#matlab

Those that are unformatted are in a satisfactory formfor the Windows version on Matlab (version 6.1) butnot on Version 5.3 under Unix.

Exercise 26.1 Suppose the numeric data is stored in afile ’table.dat’ in the form of a table, as shown below.

100 2256

200 4564

300 3653

400 6798

500 6432

The three commands,

>> fid = fopen(’table.dat’,’r’);

>> a = fscanf(fid,’%3d%4d’);

>> fclose(fid);

respectively

1. open a file for reading (this is designated by thestring ’r’). The variable fid is assigned a uniqueinteger which identifies the file used (a file iden-tifier). We use this number in all subsequent ref-erences to the file.

29

Page 46 of 96

Page 47: Simulink and Exercizes Matlab Coursebook

2. read pairs of numbers from the file with file iden-tifier fid, one with 3 digits and one with 4 digits,and

3. close the file with file identifier fid.

This produces a column vector a with elements, 1002256 200 4564 ...500 6432. This vector can be con-verted to 5× 2 matrix by the commandA = reshape(2,2,5)’;.

26.1 Formatted Files

Some computer codes and measurement instrumentsproduce results in formatted data files. In order to readthese results into Matlab for further analysis the dataformat of the files must be known. Formatted files inASCII format are written to and read from with thecommands fprintf and fscanf.

fprintf(fid, ’format’, variables) writes vari-ables an a format specified in string ’format’ tothe file with identifier fid

a = fscanf(fid, ’format’,size) assigns to vari-able a data read from file with identifier fid un-der format ’format’.

Exercise 26.2 Study the available information and helpon fscanf and fprintf commands. What is the mean-ing of the format string, ’%3d\n’?

Example 26.1 Suppose a sound pressure measurementsystem produces a record with 512 time – pressure read-ings stored on a file ’sound.dat’. Each reading is listedon a separate line according to a data format specifiedby the string, ’%8.6f %8.6f’.

A set of commands reading time – sound pressure datafrom ’sound.dat’ is,

Step 1: Assign a namestring to a file identifier.

>> fid1 = fopen(’sound.dat’,’r’);

The string ’r’ indicates that data is to be read(not written) from the file.

Step 2: Read the data to a vector named ’data’ and closethe file,

>> data = fscanf(fid1, ’%f %f’);

>> fclose(fid1);

Step 3: Partition the data in separate time and soundpressure vectors,

>> t = data(1:2:length(data));

>> press = data(2:2:length(data));

The pressure signal can be plotted in a lin-lin

diagram,

>> plot(t, press);

The result is shown in Figure 10.

Figure 10: Graph of “sound data” from Exam-ple 26.1

26.2 Unformatted Files

Unformatted or binary data files are used when small-sized files are required. In order to interpret an unfor-matted data file the data precision must be specified.The precision is specified as a string, e.g., ’float32’,controlling the number of bits read for each value andthe interpretation of those bits as character, integer orfloating point values. Precision ’float32’, for instance,specifies each value in the data to be stored as a floatingpoint number in 32 memory bits.

Example 26.2 Suppose a system for vibration mea-surement stores measured acceleration values as float-ing point numbers using 32 memory bits. The data isstored on file ’vib.dat. The following commands illus-trate how the data may be read into Matlab for analysis.

Step 1: Assign a file identifier, fid, to the string specify-ing the file name.

>> fid = fopen(’vib.dat’,’rb’);

The string ’rb’ specifies that binary numbers areto be read from the file.

Step 2 Read all data stored on file ’vib.dat’ into a vec-tor vib.

>> vib = fread(fid, ’float32’);

>> fclose(fid);

>> size(vib)

ans =

131072

The size(vib) command determines the size,i.e., the number of rows and columns of the vi-bration data vector.

In order to plot the vibration signal with a correcttime scale, the sampling frequency (the numberof instrument readings taken per second) used bythe measurement system must be known. In thiscase it is known to be 24000 Hz so that there isa time interval of 1/24000 seconds between twosamples.

30

Page 47 of 96

Page 48: Simulink and Exercizes Matlab Coursebook

Step 3: Create a column vector containing the correcttime scale.

>> dt = 1/24000;

>> t = dt*(1:length(vib))’;

Step 4: Plot the vibration signal in a lin-lin diagram

>> plot(t,vib);

>> title(’Vibration signal’);

>> xlabel(’Time,[s]’);

>> ylabel(’Acceleration, [m/s^2]’);

27 Graphic User Interfaces

The efficiency of programs that are used often and byseveral different people can be improved by simplifyingthe input and output data management. The use ofGraphic User Interfaces (GUI), which provides facilitiessuch as menus, pushbuttons, sliders etc, allow programsto be used without any knowledge of Matlab. They alsoprovides means for efficient data management.A graphic user interface is a Matlab script file cus-tomized for repeated analysis of a specific type of prob-lem. There are two ways to design a graphic user inter-face. The simplest method is to use a tool especially de-signed for the purpose. Matlab provides such a tool andit is invoked by typing ’guide’ at the Matlab prompt.Maximum flexibility and control over the programmingis, however, obtained by using the basic user interfacecommands. The following text demonstrates the use ofsome basic commands.

Example 27.1 Suppose a sound pressure spectrum isto be plotted in a graph. There are four alternative plotformats; lin-lin, lin-log, log-lin and log-log. The graphicuser interface below reads the pressure data stored on abinary file selected by the user, plots it in a lin-lin for-mat as a function of frequency and lets the user switchbetween the four plot formats.

We use two m–files. The first (specplot.m) is the maindriver file which builds the graphics window. It callsthe second file (firstplot.m) which allows the user toselect among the possible *.bin files in the current di-rectory.

% File: specplot.m

%

% GUI for plotting a user selected frequency spectrum

% in four alternative plot formats, lin-lin,

% lin-log, log-lin and log-log.

%

% Author: U Carlsson, 2001-08-22

% Create figure window for graphs

figWindow = figure(’Name’,’Plot alternatives’);

% Create file input selection button

fileinpBtn = uicontrol(’Style’,’pushbutton’,...

’string’,’File’,’position’,[5,395,40,20],...

’callback’,’[fdat,pdat] = firstplot;’);

% Press ’File’ calls function ’firstplot’

% Create pushbuttons for switching between four

% different plot formats. Set up the axis stings.

X = ’Frequency, [Hz]’;

Y = ’Pressure amplitude, [Pa]’;

linlinBtn = uicontrol(’style’,’pushbutton’,...

’string’,’lin-lin’,...

’position’,[200,395,40,20],’callback’,...

’plot(fdat,pdat);xlabel(X);ylabel(Y);’);

linlogBtn = uicontrol(’style’,’pushbutton’,...

’string’,’lin-log’,...

’position’,[240,395,40,20],...

’callback’,...

’semilogy(fdat,pdat);xlabel(X);ylabel(Y);’);

loglinBtn = uicontrol(’style’,’pushbutton’,...

’string’,’log-lin’,...

’position’,[280,395,40,20],...

’callback’,...

’semilogx(fdat,pdat);xlabel(X);ylabel(Y);’);

loglogBtn = uicontrol(’style’,’pushbutton’,...

’string’,’log-log’,...

’position’,[320,395,40,20],...

’callback’,...

’loglog(fdat,pdat);xlabel(X); ylabel(Y);’);

% Create exit pushbutton with red text.

exitBtn = uicontrol(’Style’,’pushbutton’,...

’string’,’EXIT’,’position’,[510,395,40,20],...

’foregroundcolor’,[1 0 0],’callback’,’close;’);

% Script file: firstplot.m

% Brings template for file selection. Reads

% selected filename and path and plots

% spectrum in a lin-lin diagram.

% Output data are frequency and pressure

% amplitude vectors: ’fdat’ and ’pdat’.

% Author: U Carlsson, 2001-08-22

function [fdat,pdat] = firstplot

% Call Matlab function ’uigetfile’ that

% brings file selction template.

[filename,pathname] = uigetfile(’*.bin’,...

’Select binary data-file:’);

% Change directory

cd(pathname);

% Open file for reading binary floating

% point numbers.

fid = fopen(filename,’rb’);

data = fread(fid,’float32’);

% Close file

fclose(fid);

% Partition data vector in frequency and

% pressure vectors

pdat = data(2:2:length(data));

fdat = data(1:2:length(data));

% Plot pressure signal in a lin-lin diagram

plot(fdat,pdat);

% Define suitable axis labels

xlabel(’Frequency, [Hz]’);

ylabel(’Pressure amplitude, [Pa]’);

31

Page 48 of 96

Page 49: Simulink and Exercizes Matlab Coursebook

Executing this GUI from the command line(>> specplot) brings the following screen.

Figure 11: Graph of “vibration data” from Exam-ple 27.1

Example 27.1 illustrates how the ’callback’ propertyallows the programmer to define what actions shouldresult when buttons are pushed etc. These actions mayconsist of single Matlab commands or complicated se-quences of operations defined in various subroutines.

Exercise 27.1 Five different sound recordings are storedon binary data files, sound1.bin, sound2.bin, . . . , sound5.bin.The storage precision is ’float32’ and the sounds arerecorded with sample frequency 12000 Hz.Write a graphic user interface that, opens an interfacewindow and

• lets the user select one of the five sounds,

• plots the selected sound pressure signal as a func-tion of time in a lin-lin diagram,

• lets the user listen to the sound by pushing a’SOUND’ button and finally

• closes the session by pressing a ’CLOSE’ button.

28 Command Summary

The command>> help

will give a list of categories for which help is available(e.g. matlab/general covers the topics listed in Table 3.Further information regarding the commands listed inthis section may then be obtained by using:>> help topic

try, for example,>> help help

abs Absolute valuesqrt Square root functionsign Signum functionconj Conjugate of a complex numberimag Imaginary part of a complex

numberreal Real part of a complex numberangle Phase angle of a complex numbercos Cosine functionsin Sine functiontan Tangent functionexp Exponential functionlog Natural logarithmlog10 Logarithm base 10cosh Hyperbolic cosine functionsinh Hyperbolic sine functiontanh Hyperbolic tangent functionacos Inverse cosineacosh Inverse hyperbolic cosineasin Inverse sineasinh Inverse hyperbolic sineatan Inverse tanatan2 Two–argument form of inverse

tanatanh Inverse hyperbolic tanround Round to nearest integerfloor Round towards minus infinityfix Round towards zeroceil Round towards plus infinityrem Remainder after division

Table 2: Elementary Functions

32

Page 49 of 96

Page 50: Simulink and Exercizes Matlab Coursebook

Managing commands and functions.help On-line documentation.doc Load hypertext documentation.what Directory listing of M-, MAT-

and MEX-files.type List M-file.lookfor Keyword search through the

HELP entries.which Locate functions and files.demo Run demos.

Managing variables and the workspace.who List current variables.whos List current variables, long form.load Retrieve variables from disk.save Save workspace variables to disk.clear Clear variables and functions

from memory.size Size of matrix.length Length of vector.disp Display matrix or text.Working with files and the operating system.cd Change current working direc-

tory.dir Directory listing.delete Delete file.! Execute operating system com-

mand.unix Execute operating system com-

mand & return result.diary Save text of MATLAB session.

Controlling the command window.cedit Set command line edit/recall fa-

cility parameters.clc Clear command window.home Send cursor home.format Set output format.echo Echo commands inside script

files.more Control paged output in com-

mand window.Quitting from MATLAB.

quit Terminate MATLAB.

Table 3: General purpose commands.

Matrix analysis.cond Matrix condition number.norm Matrix or vector norm.rcond LINPACK reciprocal condition

estimator.rank Number of linearly independent

rows or columns.det Determinant.trace Sum of diagonal elements.null Null space.orth Orthogonalization.rref Reduced row echelon form.

Linear equations.\ and / Linear equation solution; use

“help slash”.chol Cholesky factorization.lu Factors from Gaussian elimina-

tion.inv Matrix inverse.qr Orthogonal- triangular decompo-

sition.qrdelete Delete a column from the QR fac-

torization.qrinsert Insert a column in the QR factor-

ization.nnls Non–negative least- squares.pinv Pseudoinverse.lscov Least squares in the presence of

known covariance.Eigenvalues and singular values.

eig Eigenvalues and eigenvectors.poly Characteristic polynomial.polyeig Polynomial eigenvalue problem.hess Hessenberg form.qz Generalized eigenvalues.rsf2csf Real block diagonal form to com-

plex diagonal form.cdf2rdf Complex diagonal form to real

block diagonal form.schur Schur decomposition.balance Diagonal scaling to improve

eigenvalue accuracy.svd Singular value decomposition.

Matrix functions.expm Matrix exponential.expm1 M- file implementation of expm.expm2 Matrix exponential via Taylor se-

ries.expm3 Matrix exponential via eigenval-

ues and eigenvectors.logm Matrix logarithm.sqrtm Matrix square root.funm Evaluate general matrix function.

Table 4: Matrix functions—numerical linear alge-bra.

33

Page 50 of 96

Page 51: Simulink and Exercizes Matlab Coursebook

Graphics & plotting.figure Create Figure (graph window).clf Clear current figure.close Close figure.subplot Create axes in tiled positions.axis Control axis scaling and appear-

ance.hold Hold current graph.figure Create figure window.text Create text.print Save graph to file.plot Linear plot.loglog Log-log scale plot.semilogx Semi-log scale plot.semilogy Semi-log scale plot.

Specialized X-Y graphs.polar Polar coordinate plot.bar Bar graph.stem Discrete sequence or ”stem” plot.stairs Stairstep plot.errorbar Error bar plot.hist Histogram plot.rose Angle histogram plot.compass Compass plot.feather Feather plot.fplot Plot function.comet Comet-like trajectory.

Graph annotation.title Graph title.xlabel X-axis label.ylabel Y-axis label.text Text annotation.gtext Mouse placement of text.grid Grid lines.contour Contour plot.mesh 3-D mesh surface.surf 3-D shaded surface.waterfall Waterfall plot.view 3-D graph viewpoint specifica-

tion.zlabel Z-axis label for 3-D plots.gtext Mouse placement of text.grid Grid lines.

Table 5: Graphics & plot commands.

34

Page 51 of 96

Page 52: Simulink and Exercizes Matlab Coursebook

Index

<, 21, 23<=, 21, 23==, 21, 23>, 21, 23>=, 21, 23%, 10, 24’, 5.’, 6.*, 11..., 8./, 12.^, 12:, 5, 16;, 4

abs, 32accelerators

keyboard, 9and, 22angle, 32ans, 3array, 13axes, 9, 13axis, 9

auto, 9normal, 9square, 9

browser, 29

ceil, 32clf, 8close, 8colon notation, 5, 16column vectors, 5comment (%), 10, 24complex

conjugate transpose, 6numbers, 6

complex numbers, 3components of a vector, 4conj, 32contour, 28copying output, 10cos, 32CPU, 28cursor keys, 9

demo, 3diag, 15diary, 6dice, 26divide

dot, 12documentation, 29dot

divide ./, 12power .^, 12product .*, 11, 16

echo, 10elementary functions, 4eye, 14ezplot, 7

false, 21Fibonnaci, 21, 24figure, 8file

function, 23script, 10

find, 27fix, 32floor, 32floor, 26for

loop, 20format, 3

long, 12function m–files, 23functions

elementary, 4trigonometric, 4

get, 9graphs, see plottinggrid, 7, 13, 28GUI, 31

hard copy, 8help, 2, 24hold, 7, 13home page, 29

if statement, 23imag, 32

keyboard accelerators, 9

labels for plots, 7legend, 7length of a vector, 4, 5, 11line styles, 7linspace, 6logical conditions, 21loops, 20

while, 22

m–files, 10, 23matrix, 13

building, 15diagonal, 15identity, 14indexing, 16n=5;tridiagonal, 17orthogonal, 26size, 14sparse, 17special, 14spy, 15

35

Page 52 of 96

Page 53: Simulink and Exercizes Matlab Coursebook

square, 14symmetric, 14zeros, 14

matrix products, 17matrix–vector products, 16max, 26, 28mesh, 28meshgrid, 27min, 26, 28more, 3multi–plots, 7

Netscape, 29norm of a vector, 11not, 21–23numbers, 3

complex, 3format, 3random, 26rounding, 25

ones, 14or, 22

plot, 20plotting, 6, 13, 27

labels, 7line styles, 7printing, 8surfaces, 27title, 7

powerdot, 12

printing plots, 8priorities

in arithmetic, 3product

dot, 11, 16scalar, 16, 17

quit, 2

rand, 26random numbers, 26real, 32rem, 32round, 32rounding error, 4rounding numbers, 25

save, 6scalar product, 11, 16, 17script files, 10semi–colon, 4, 13set, 9shapes, 7sign, 32sin, 32size, 14sort, 5sparse, 17spdiags, 17

spy, 15sqrt, 32strings, 7subplot, 8, 20subscripts, 9sum, 21, 25superscripts, 9surfing the internet highway, 29

timing, 28title for plots, 7toc, 28transposing, 5tridiagonal, 17trigonometric functions, 4true, 21type (list contents of m-file), 10

variable names, 3vector

components, 4vectors

column, 5row, 4

what, 10while loops, 22whos, 6WWW, 29

xlabel, 7, 28xterm, 2

ylabel, 7

zeros, 14zoom, 8

36

Page 53 of 96

Page 54: Simulink and Exercizes Matlab Coursebook

An example of solving ODEs in MatLab 7 Figure 1 shows the thermal analog of heat transfer in a single material:

TTi 1R1 R2

C1

T2R3

C2

T T3R4

C3

eTTT

TiTTT TeTT

Figure 1. The thermal analog heat transfer in a single material Using the method presented at the course, the ODEs are:

3/

2/

1/

4

3

3

323

3

32

2

212

2

21

1

11

CRTT

RTT

dtdT

CRTT

RTT

dtdT

CRTT

RTT

dtdT

e

i

⎟⎟⎠

⎞⎜⎜⎝

⎛ −−

−=

⎟⎟⎠

⎞⎜⎜⎝

⎛ −−

−=

⎟⎟⎠

⎞⎜⎜⎝

⎛ −−

−=

Implementation: Step 0: Run MatLab Step 1: Write mfile ‘odexfun.m’ containg the ODEs Step 2: Write second mfile ‘odexst.m’ to start simulation and plotting of the results Step 3: type ‘odexst’ at the matlab prompt

Page 54 of 96

Page 55: Simulink and Exercizes Matlab Coursebook

Step 1 (‘odexfun.m’) %ODEXFUN ODE EXample FUNction % % JvS 2010/Feb function xdot=odexfun(t,x) %x(1)=T1 %x(2)=T2; %x(3)=T3; % Wall properties: A=1; % m2 k=1; % W/mK c=840; % J/KgK rho=1200; %kg/m3 d=0.2; %m % External conditions Te=0; %oC h_e=25; %W/m2K % Internal boundry Ti=20; %oC h_i=7.7; %W/m2K % R's [K/W] R1=1/(A*h_e); R2=(d/2) / (A*k) ; R3=(d/2) / (A*k) ; R4=1/(A*h_i); %C's [J/K] Ctotal=rho*c*A*d; C1=Ctotal/4; C2=Ctotal/2; C3=Ctotal/4; xdot=zeros(3,1); %Te=10*sin(t/3600); % You may try this xdot(1)=( (Ti -x(1))/R1 - (x(1)-x(2))/R2 )/C1; xdot(2)=( (x(1)-x(2))/R2 - (x(2)-x(3))/R3 )/C2; xdot(3)=( (x(2)-x(3))/R3 - (x(3)-Te )/R4 )/C3;

Page 55 of 96

Page 56: Simulink and Exercizes Matlab Coursebook

Step 2 (‘odexst.m’) %ODEXST ODE EXample STart % % JvS 2010/Feb clear all % Start/end time in seconds: tbegin=0; tend=48*3600; % Initial values T0=[T1;T2;T3] T0=[0; 0; 0]; % Start simulation [t,x]=ode23s(@odexfun,[tbegin tend],T0); % Plot result plot(t,x) xlabel('t [s] ') ylabel('T [oC] ') legend('T1','T2','T3') grid

Result

0 2 4 6 8 10 12 14 16 18

x 104

0

2

4

6

8

10

12

14

16

18

t [s]

T [o

C]

T1T2T3

Page 56 of 96

Page 57: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 1

SIMULINK® TUTORIAL

The Intelligent Structures and Systems LaboratoryDepartment of Mechanical Engineering

The Ohio-State UniversityColumbus OH 43210.

Prepared by Arun Rajagopalan and Gregory WashingtonSpring 2002.

Page 57 of 96

Page 58: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 2

TABLE OF CONTENTS

TABLE OF CONTENTS..........................................................................................................2

LIST OF FIGURES ..................................................................................................................3

INTRODUCTION: CONCEPT OF DYNAMIC SYSTEM SIMULATION ..........................4

CONCEPT OF SIGNAL AND LOGIC FLOW......................................................................................4CONNECTING BLOCKS...............................................................................................................6

SOURCES AND SINKS ...........................................................................................................7

CONTINUOUS AND DISCRETE SYSTEMS ........................................................................8

NON-LINEAR OPERATORS................................................................................................12

USING FUNCTIONS (WRITTEN AS M, C, ETC..) ............................................................15

MATHEMATICAL OPERATIONS......................................................................................17

SIGNALS & DATA TRANSFER...........................................................................................18

OPTIMIZING VISUAL APPEAL.........................................................................................19

USE OF SUBSYSTEMS AND MASKS............................................................................................19MAKING SUBSYSTEMS............................................................................................................23VISUAL AIDS..........................................................................................................................26

SETTING SIMULATION PARAMETERS ..........................................................................28

CONCEPT OF HARDWARE IN THE LOOP......................................................................29

TIPS AND TRICKS................................................................................................................30

RESOURCES..........................................................................................................................31

Page 58 of 96

Page 59: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 3

LIST OF FIGURES

Figure 1: Simulink Library..........................................................................................................5Figure 2: Connecting blocks........................................................................................................6Figure 3: Sources and Sinks ........................................................................................................7Figure 4: Continuous and Discrete Systems ................................................................................8Figure 5: Advanced Linear Systems............................................................................................8Figure 6: A mass-spring-damper system – an example of a 2nd order dynamic system...............11Figure 7: Non-linearities ...........................................................................................................12Figure 8: Example of a non-linear function (saturation).............................................................13Figure 9: Mass-Spring-Damper system with Coulomb friction..................................................13Figure 10: Output of mass-spring-damper system with coulomb friction...................................14Figure 11: Functions and tables.................................................................................................15Figure 12: 2-D Look-up table example......................................................................................16Figure 13: Visualization of the 2-D look-up table......................................................................16Figure 14: Mathematical tools...................................................................................................17Figure 15: Signals and data transfer ..........................................................................................18Figure 16: Subsystems ..............................................................................................................19Figure 17: Masking example – PID control block .....................................................................20Figure 18: Programming the mask ............................................................................................21Figure 19: Simplification using subsystems...............................................................................22Figure 20: Create a subsystem...................................................................................................23Figure 21: Create input / output ports ........................................................................................24Figure 22: Create hidden code...................................................................................................25Figure 23: Setting block display features...................................................................................26Figure 24: Example of block display options.............................................................................27Figure 25: Simulation settings...................................................................................................28Figure 26: Available numerical methods for solving dynamic equations ...................................28Figure 27: Concept of Hardware in the Loop.............................................................................29Figure 28: Example of Hardware in the Loop............................................................................29Figure 29: Providing compatibility with earlier versions of Simulink ........................................30

Page 59 of 96

Page 60: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 4

Introduction: Concept of Dynamic System Simulation

Computers have provided engineers with immense mathematical powers, which can beused to simulate (or mimic) dynamic systems without the actual physical setup. Simulation ofDynamic Systems has proved to be immensely useful when it comes to control design, savingtime and money that would otherwise be spent in prototyping a physical system. Simulink is asoftware add-on to MATLAB® which is a mathematical tool developed by The Mathworks,(http://www.mathworks.com) a company based in Natick, MA. MATLAB is powered byextensive numerical analysis capability. Simulink® is a tool used to visually program a dynamicsystem (those governed by Differential equations) and look at results. Any logic circuit, or acontrol system for a dynamic system can be built by using standard BUILDING BLOCKSavailable in Simulink Libraries. Various toolboxes for different techniques, such as Fuzzy Logic,Neural Networks, DSP, Statistics etc. are available with Simulink, which enhance the processingpower of the tool. The main advantage is the availability of templates / building blocks, whichavoid the necessity of typing code for small mathematical processes.

Concept of signal and logic flow

In Simulink, data/information from various blocks are sent to another block by linesconnecting the relevant blocks. Signals can be generated and fed into blocks (dynamic / static).Data can be fed into functions. Data can then be dumped into sinks, which could be scopes,displays or could be saved to a file. Data can be connected from one block to another, can bebranched, multiplexed etc. In simulation, data is processed and transferred only at Discretetimes, since all computers are discrete systems. Thus, a SIMULATION time step (otherwisecalled an INTEGRATION time step) is essential, and the selection of that step is determined bythe fastest dynamics in the simulated system. In the following sections, the different blocks thatare available are explained. Figure 1 shows the overview of the Simulink libraries available.More toolboxes may be available based on what has been purchased. The latest version isSimulink 4.0, which is used with MATLAB 6.1 (Release 12.1).

Page 60 of 96

Page 61: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 5

Figure 1: Simulink Library

Page 61 of 96

Page 62: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 6

Connecting blocks

To connect blocks, left-click and drag the mouse from the output of one block to the inputof another block. Figure 2 shows the steps involved. Tips for branches and quick connections areprovided at the end of this document.

Figure 2: Connecting blocks

Page 62 of 96

Page 63: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 7

Sources and Sinks

The sources library contains the sources of data/signals that one would use in a dynamicsystem simulation. One may want to use a constant input, a sinusoidal wave, a step, a repeatingsequence such as a pulse train, a ramp etc. One may want to test disturbance effects, and can usethe random signal generator to simulate noise. The clock may be used to create a time index forplotting purposes. The ground could be used to connect to any unused port, to avoid warningmessages indicating unconnected ports.

The sinks are blocks where signals are terminated or ultimately used. In most cases, wewould want to store the resulting data in a file, or a matrix of variables. The data could bedisplayed or even stored to a file. The STOP block could be used to stop the simulation if theinput to that block (the signal being sunk) is non-zero. Figure 3 shows the available blocks in thesources and sinks libraries. Unused signals must be terminated, to prevent warnings aboutunconnected signals.

Figure 3: Sources and Sinks

Page 63 of 96

Page 64: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 8

Continuous and Discrete Systems

All dynamic systems can be analyzed as continuous or discrete time systems. Simulinkallows you to represent these systems using transfer functions, integration blocks, delay blocksetc.

Figure 4: Continuous and Discrete Systems

Figure 4 shows the available dynamic systems blocks. Discrete systems could bedesigned in the Z-plane, representing difference equations. Systems could be represented inState-space forms, which are useful in Modern Control System design.

Figure 5 contains some advanced linear blocks, available in the “Simulink Extras”library. They contain certain advanced blocks, such as a PID control block, transfer functionswith initial conditions, etc.

Figure 5: Advanced Linear Systems

Page 64 of 96

Page 65: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 9

EXAMPLE of a dynamic system: A mass-spring-damper system

The following section contains an example for building a mass-spring-damper system.The system can be built using two techniques: a state space representation, used in moderncontrol theory, and one using conventional transfer functions. The mass-spring-damper system isa second order system, which is commonly encountered in system dynamics. ElectricalResistance-Inductance-Capacitance (RLC) circuits are also analogous to this example, and canbe modeled as 2nd order systems.

The example is shown in Figure 6. A step input is used as the control input. (It is an openloop example). The top portion of the block contains the transfer function representation of thedynamic system. We can observe only the outputs, and cannot monitor the states. Also, initialconditions cannot be specified. (By using the special transfer function block in theSimulink\Extras toolbox, initial conditions can be specified). The bottom portion of the Simulinkdiagram shows the same 2nd order system in state space representation. The highest derivative(acceleration in our case) is represented as a function of the input and the other states. This inputis integrated to form the next lower state. Initial conditions for each state can be specified in theintegration block. States can be individually monitored and manipulated.

Consider a mass-spring damper with the following dynamic equation:

m˙ x + c˙ x + kx = qiu (1)

wherex Output variablem Massc Damping coefficientk Spring stiffnessu Control force ( multiplied by a constant qi)

It can be represented in Laplace domain (as a transfer function) as follows:

a

X(s)U(s)

=KwN

2

s2 + 2VwN s + wN2 (2)

where

V Damping coefficient

z =c

2 k ⋅ m

Nw Natural frequency

wn =km

K Steady State gain (or Static sensitivity)

K =qi

m

In the state formulation the system is represented in terms of it’s highest derivative:

Page 65 of 96

Page 66: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 10

From (1)

m˙ x = (qiu - c˙ x - kx) Æ ˙ x = 1m

(qiu - c˙ x - kx) (3)

or it can also be written in terms of it’s damping and natural frequency as (with

qi =1):

˙ x = um

- 2VwN ˙ x -wN2x (4)

In our example below, with zero initial conditions, both the transfer function and the staterepresentations provide similar results. In general both diagrams are NOT necessary. The stepsfor the state formulation are as follows:

1. Solve the differential equation in question for the highest derivative. If the equation is notnormalized (as in the first of equation 3) the highest derivative may be multiplied by a term.You can divide all the values by that term as was done in the second part of equation 3. Youshould now have your single term with the highest derivative on the left side and the rest ofthe terms on the right side of the equation.

2. Draw a summer block. The block should have as many plusses and minuses as there areterms in the right side of the equation (in equation (3) we have 3 components and two ofthem are negative, thus we add 2 minus sings and 1 plus sign to our summer). The output ofthe summing block should equal the highest derivative term multiplied by a constant. Youcan now multiply or divide the constant out to get the derivative by itself.

3. Add integrators. The total number of integrators should equal the total number of derivativesthat you want to remove. For example, if you have a second order mechanical system (likethe one in equation 3) and you want position, you need to integrate twice. Put a block at theend for the output variable.

4. After each integrator, feed the signal back to its proper place on the summer. Immediately tothe right of an integrator is a value equal to the integral of the value on the left. Be sure touse a gain block to multiply any value by its proper constant before feeding the value back.

Notice in the state formulation example that the lower derivatives (or states) are accessible(Internal Variables). This accessibility makes the state formulation a better methodology fordynamic systems classes. In addition, it is easier to adapt the system to nonlinear components.The transfer function methodology is simpler (only one block), but it is limited in is application.

Page 66 of 96

Page 67: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 11

Figure 6: A mass-spring-damper system – an example of a 2nd order dynamic system

Transfer functionrepresentation

State-Spacerepresentation

Page 67 of 96

Page 68: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 12

Non-linear operators

A main advantage of using tools such as Simulink is the ability to simulate non-linearsystems and arrive at results without having to solve analytically. It is very difficult to arrive atan analytical solution for a system having non-linearities such as saturation, signum function,limited slew rates etc. In Simulation, since systems are analyzed using iterations, non-linearitiesare not a hindrance. Figure 7 shows the non-linear components that can be incorporated into asimulation. One such could be a saturation block, to indicate a physical limitation on aparameter, such as a voltage signal to a motor etc. Manual switches are useful when tryingsimulations with different cases. Switches are the logical equivalent of IF-THEN statements inprogramming. Slew rates using the rate limiter could control the rate of change of a physicalparameter, such as the speed of a DC motor, etc.

Figure 7: Non-linearities

EXAMPLE:Here is an example using a non-linear block. Consider a sine wave of amplitude 1 (signal

varies between +1 and –1). A saturation block is used to limit the output to an amplitude of 0.5and the saturated and unsaturated (original) signals are compared. The example is shown inFigure 8. The saturated and unsaturated signals are clearly seen.

Page 68 of 96

Page 69: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 13

Figure 8: Example of a non-linear function (saturation)

EXAMPLE of a dynamic system: A mass-spring-damper system with Coulomb Friction

A mass-spring-damper system is created with Coulomb friction for the damper force.The Coulomb friction (from the non-linear library block) is represented as an offset at zerovelocity. The offset for our example is given as 0.5 (with a slope of 1). The coding is shown inFigure 9. The output for a combination input = ramp(2t) + step + ramp (5t) is shown in Figure10. The combination input is available as the repeating sequence in the sources library block. Asexpected, the Coulomb Friction creates undesired response in the output of the system.

Figure 9: Mass-Spring-Damper system with Coulomb friction

CoulombFriction with anoffset of 0.5

Page 69 of 96

Page 70: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 14

Figure 10: Output of mass-spring-damper system with coulomb friction

Page 70 of 96

Page 71: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 15

Using functions (written as M, C, etc..)

Functions written in M or in any other language such as C or Fortran could be used inconjunction with Simulink to enhance the computing power of Simulink. Custom code, ifincluded, written as an ‘M’ or ‘C’ file, are evaluated at every simulation step. S-functions areDynamic Linked Libraries (DLL) written in another language such as C, and then compiledusing the MATLAB compiler ‘MEX’. This is useful in large simulations, since a function writtenin ‘C’ runs much faster than a comparably programmed M-function. Also, for REAL-TIMEsimulations, only S-functions can be used, the reason again being high speed of processing.

Figure 11: Functions and tables

Look-up tables are very useful in mapping different data points and functions. N-dimensional look-up tables are available. Figure 11 shows the various functions and tables usedin Simulink.

EXAMPLE:

Look-up tables are used for producing outputs based on a pattern of inputs. If the patternis known, then the data could be entered in a Look-up table, and linear interpolation is performedto produce the outputs based on the new set of inputs. Consider the simple example where youwant to multiply 2 inputs and get the output. A 2-D look-up table is created in Simulink, and thevalues for 1, 2 and 3 as inputs are entered in the output block, as seen in Figure 12. The block isused to multiply 2 inputs, and the output is shown as follows:

2 * 2.5 = 5

Page 71 of 96

Page 72: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 16

Figure 12: 2-D Look-up table example

The visualization of the 2-D look-up table is shown in Figure 13. Any 2-D surface can berepresented as a look-up table if data exists for specific points on the inputs. 1-D and n-D look-up tables are also available in Simulink.

Figure 13: Visualization of the 2-D look-up table

Page 72 of 96

Page 73: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 17

Mathematical operations

Mathematical operators such as products, sum, logical operations such as AND, OR, etc.can be programmed along with the signal flow. Matrix multiplication becomes easy with thematrix gain block. Trigonometric functions such as sin or tan inverse (atan) are also available.

Relational operators such as ‘equal to’, ‘greater than’ etc. can also be used in logiccircuits. Figure 14 depicts the available mathematical tools in Simulink 4.0.

Figure 14: Mathematical tools

Page 73 of 96

Page 74: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 18

Signals & Data Transfer

In complicated block diagrams, there may arise the need to transfer data from one portionto another portion of the block. They may be in different subsystems. That signal could bedumped into a GOTO block, which is used to send signals from one subsystem to another.Multiplexing helps us remove clutter due to excessive connectors, and makes matrix(column/row) visualization easier.

Figure 15: Signals and data transfer

Page 74 of 96

Page 75: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 19

Optimizing Visual appeal

Many times, when a complex Simulink diagram is built, the number of connectors andblocks on a particular level may prevent proper comprehension of the flow of logic. In suchcases, one can create a hierarchical flow of blocks using subsystems, which help keep the blockdiagram simple and comprehendible.

Use of subsystems and masks

Masks are interfaces between the functionality of a subsystem and the user. For example,if there exists an algorithm that the programmer would like to hide from the user, or will be tooconfusing for the user, the programmer uses a mask and hides the algorithm after placing it in asubsystem.

Figure 16: Subsystems

Page 75 of 96

Page 76: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 20

Example: (PID control block in Simulink\Extras)

The ‘Simulink Extras’ block, contains a PID controller. When double-clicked, it asks theuser for the P, I and D gains of the system. The system inside (which can be observed by right-clicking on the block and clicking on ‘Look under mask’) is shown in Figure 17.

Figure 17: Masking example – PID control block

Page 76 of 96

Page 77: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 21

The following illustrations in Figure 18 show the components of the mask. There are spacesprovided for typing help messages, sketching figures on the face of the block, accepting variablesand creating prompts, etc.

Figure 18: Programming the mask

Page 77 of 96

Page 78: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 22

EXAMPLE: Simplification of the block diagram

In case of complex block diagrams, cluttering of smaller blocks makes the block difficultto understand. In that case, based on functionality, blocks from the main window can be placedinside sub-systems and the subsystems make up the main block. Figure 19 shows an example of adynamic system with a feedback controller and actuator dynamics. The three functional modulesare now placed in their respective subsystems.

Figure 19: Simplification using subsystems

Page 78 of 96

Page 79: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 23

Making Subsystems

The following is the procedure for making subsystems such as the block in Figure 19.

1. Drag a subsystem from the Simulink Library Browser and place it in the parent blockwhere you would like to hide the code. The type of subsystem depends on the purpose ofthe block. In general one will use the standard subsystem but other subsystems can bechosen. For instance, the subsystem can be a triggered block, which is enabled onlywhen a trigger signal is received. Figure 20 shows the procedure for creating a subsystemblock.

Figure 20: Create a subsystem

Page 79 of 96

Page 80: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 24

2. Open (double click) the subsystem and create input / output PORTS, which transfersignals into and out of the subsystem. The input and output ports are created by draggingthem from the Sources and Sinks directories respectively. When ports are created in thesubsystem, they automatically create ports on the external (parent) block. This allows forconnecting the appropriate signals from the parent block to the subsystem. Figure 21shows the creation of the input / output ports.

Figure 21: Create input / output ports

Internal Input /Output PORTS

External Input /Output PORTS

Page 80 of 96

Page 81: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 25

3. Once the subsystem is created create blocks or code to be enclosed. This is shown in thebottom part of Figure 22. These blocks contain the code that would be hidden from theparent block and they communicate with the parent block using the Input / outputPORTS. Figure 22 shows how the hidden code uses the input output ports tocommunicate to the parent block.

Figure 22: Create hidden code

The subsystem can then be masked if necessary.

Hidden code

Input / output ports

Page 81 of 96

Page 82: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 26

Visual aids

The following visual aids can be used to provide more information about the simulatedblock.

- Sample time colorsBased on the sampling rate of the system and their individual components, colors areassigned automatically to systems with different sampling rates.

- Signal TypeBased on the type of signal, whether double, Boolean etc., signals ca be labeled, that helpus identify what each signal represents.

- VECTOR Wide lines and line WIDTHThe width of lines can be changed based on whether they transmit scalars or vectors.Wider lines represent vectors. The actual width (no. of multiplexed data signals) can alsolabeled next to the lines.

- Execution orderSometimes, it is useful to know the order of execution of the blocks in the Simulinkdiagram. This command places a number next to the specific block indicating its order ofexecution.

The commands are shown in Figure 23. A sample of the features is displayed in Figure 24.

Figure 23: Setting block display features

Page 82 of 96

Page 83: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 27

Figure 24: Example of block display options

SIGNAL TYPEEXECUTIONORDER

VECTORWIDE LINESand WIDTH

Page 83 of 96

Page 84: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 28

Setting simulation parameters

Running a simulation in the computer always requires a numerical technique to solve adifferential equation. The system can be simulated as a continuous system or a discrete systembased on the blocks inside. The simulation start and stop time can be specified. In case ofvariable step size, the smallest and largest step size can be specified. A Fixed step size isrecommended and it allows for indexing time to a precise number of points, thus controlling thesize of the data vector. Simulation step size must be decided based on the dynamics of thesystem. A thermal process may warrant a step size of a few sconds, but a DC motor in the systemmay be quite fast and may require a step size of a few milliseconds.

Figure 25: Simulation settings

Figure 26: Available numerical methods for solving dynamic equations

Page 84 of 96

Page 85: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 29

Concept of Hardware in the Loop

Simulink’s REAL TIME WORKSHOP (RTW) provides the ability to link Simulink toany hardware available, thus providing control capability firectly from a high-level programminglanguage like MATLAB/Simulink. This concept, known as Hardware-in-the-Loop (HIL) is usedextensively in control development. The concept of Real-time control using hardware in the loopis explained below.

Figure 27: Concept of Hardware in the Loop

An example is shown below in Figure 28. A first order model is replaced by a DAC and an ADCfeeding information from and to the actual hardware. The DAC signal is sent to an actuator, andthe ADC signal is acquired from a sensor. An example of a Real-time control system is dSPACE,who provide the hardware (data acquisition and connectivity boards) and the necessaryhardware-software interfaces in Simulink. The interface blocks are available from a dSPACElibrary in Simulink.

Figure 28: Example of Hardware in the Loop

Page 85 of 96

Page 86: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 30

Tips and Tricks

Here are some useful tips for working with Simulink.

1. To copy a block, right click and drop the block onto the target Simulink window.

2. LIBRARIESTo create a template block, save the Simulink block as a library. In the future, you cancopy the block from the library onto any Simulink block where it needs to be used.Changing the block structure or parameters in the library activates the changes in all theblocks where they may be used. If you want to break the link of a particular block fromits library source, right-click and say “Break Library Link”.

3. To create a branch from a signal, right click on the source signal at the point where youwould like to branch to start, and drag it to the target location.

4. Always connect all open ports in a block diagram, to prevent warnings aboutunconnected ports. Ground (in Sources) and terminator (in Sinks) can be used to plugopen ports.

5. Compatibility with older versions of MATLABSimulink files saved in MATLAB 6 (Release 12) / Simulink 4 or MATLAB 6.1 (Release12.1) / Simulink 4.1 may not be compatible with MATLAB 5.3 (Release 11) / Simulink3.0 and earlier versions. To provide compatibility, specify the type when saving theSimulink block, as shown below in Figure 29.

Figure 29: Providing compatibility with earlier versions of Simulink

Page 86 of 96

Page 87: Simulink and Exercizes Matlab Coursebook

Simulink Tutorial © 2002 – OSU-ME

Revised 7/31/02 31

Resources

The Mathworks Website (contains online documentation)http://www.mathworks.com

Control System Analysis using MATLABhttp://rclsgi.eng.ohio-state.edu/matlab

Simulink Tutorial by T. Nuygenhttp://www.messiah.edu/acdept/depthome/engineer/Resources/tutorial/matlab/simu.html

MATLAB/Simulink Resourceshttp://www.eng.fsu.edu/~cockburn/matlab/matlab_help.html

Simulink: A graphical tool for dynamic system simulation (by G.D. Buckner, NCSU)http://www.mae.ncsu.edu/org/asme/webpages/tutorial1.pdf

Page 87 of 96

Page 88: Simulink and Exercizes Matlab Coursebook

7S800

INTRODUTION TO SYSTEM SIMULATION

Modeling & Simulation of a heat pump in SimuLink

by Jos van Schijndel

http://sts.bwk.tue.nl/7y530/

Goals:- modeling of a heat pump- simulation in SimuLink- combined simulation of building, heat pump and on/off controller

Contents

1. Model of a Heat Pump

2. Models

2.1 static, constant COP , energy based

2.2 statistic, constant COP , mass flow/temperature based

2.3 dynamic, variable COP, mass flow/temperature based

3. Combined Simulation of a heat pump, building and on/off controller

Page 88 of 96

Page 89: Simulink and Exercizes Matlab Coursebook

1. Model of a Heat Pump

Equations:

o

o o

oTverd_in

Tverd_uit

Tcond_in

Tcond_uit

oqaf qtoe

w

qtoeTverduitTverdincmdt

dTverduitC

qafTconduitTcondincmdt

dTconduitC

wCOPwqtoeqafwCOPqtoe

TverduitTconduitTconduitAcarnotCOP

verd

cond

+−⋅⋅=

−−⋅⋅=

⋅−=−==

−+⋅⋅=

)(

)(

)1(*

15.273

&

&

η

Page 89 of 96

Page 90: Simulink and Exercizes Matlab Coursebook

2.1 static, constant COP , energy based

Model: ECOPQ ⋅=

SimuLink Model:

Exercise 1: Simulate this model in SimuLink and evaluate the result

WarmtePomp Very Simple

1000

E 3000

Display3

COP

Page 90 of 96

Page 91: Simulink and Exercizes Matlab Coursebook

2.2 statistic, constant COP , mass flow/temperature based

Model:

MatLab function:

%WPSIMPLEFUN% JvS 2000

function y=wpsimplefun(x)

mcv=x(1); %mdot*c verdamper, [J/Ks],entropiestroomTv_in=x(2);%temperatuur verdamper [oC]mcc=x(3); %mdot*c condensor, [J/Ks],entropiestroomTc_in=x(4);%temperatuur condensor [oC]E=x(5); %Electrisch vermogen [W]COP=x(6); % COP [-]

Qtoe=COP*E;Qaf=(COP-1)*E;Tc_uit=Tc_in-Qaf/mcc;Tv_uit=Tv_in+Qtoe/mcv;

y=[Tv_uit;Tc_uit;Qtoe];

cmECOPTverdinTverduit

cmECOPTcondinTconduit

verd

cond

⋅⋅+=

⋅⋅−−=

&

&

)1(

Page 91 of 96

Page 92: Simulink and Exercizes Matlab Coursebook

SimuLink Model:

Excercise 2: Simulate this model in SimuLink and evaluate the result

500

mcv

500

mccMATLABFunction

Warmtepomp simpe

39.6

Tv_uit

30

Tv

3.4

Tc_uit10

Tc

4800

Qverwarming

1500

E

m

3.2

COP

Page 92 of 96

Page 93: Simulink and Exercizes Matlab Coursebook

2.3 dynamic, variable COP, mass flow/temperature based

Model:

SFunction (see 'wpsfun2.m'):

function [sys,x0,str,ts] = wpsfun2(t,x,u,flag)%WPSFUN1 Voorbeeld van een warmtepomp diff. vgl systeem%%JvS Mei 2000%%%u(1)=Tvi%u(2)=Fv [kg/s]%u(3)=Tci%u(4)=Fci [kg/s]%u(5)=Ewp%u(6)=COP0 (k)%y(1)=Tve=x(1)%y(2)=Tce=x(2)%y(3)=COP

switch flag,

%%%%%%%%%%%%%%%%%% % Initialization % %%%%%%%%%%%%%%%%%% case 0, [sys,x0,str,ts]=mdlInitializeSizes;

%%%%%%%%%%%%%%% % Derivatives % %%%%%%%%%%%%%%% case 1, sys=mdlDerivatives(t,x,u);

qtoeTverduitTverdincmdt

dTverduitC

qafTconduitTcondincmdt

dTconduitC

wCOPwqtoeqafwCOPqtoe

TverduitTconduitTconduitAcarnotCOP

verd

cond

+−⋅⋅=

−−⋅⋅=

⋅−=−==

−+⋅⋅=

)(

)(

)1(*

15.273

&

&

η

Page 93 of 96

Page 94: Simulink and Exercizes Matlab Coursebook

%%%%%%%%%%% % Outputs % %%%%%%%%%%% case 3, sys=mdlOutputs(t,x,u);

%%%%%%%%%%%%%%%%%%% % Unhandled flags % %%%%%%%%%%%%%%%%%%% case 2, 4, 9 , sys = [];

%%%%%%%%%%%%%%%%%%%% % Unexpected flags % %%%%%%%%%%%%%%%%%%%% otherwise error(['Unhandled flag = ',num2str(flag)]);

end% end wpfun1

%%=============================================================================% mdlInitializeSizes% Return the sizes, initial conditions, and sample times for the S-function.%=============================================================================%function [sys,x0,str,ts]=mdlInitializeSizes

sizes = simsizes;sizes.NumContStates = 2;sizes.NumDiscStates = 0;sizes.NumOutputs = 4;sizes.NumInputs = 6;sizes.DirFeedthrough = 1;sizes.NumSampleTimes = 1;

sys = simsizes(sizes);x0 = [20; 40];str = [];ts = [0 0];

% end mdlInitializeSizes%%=============================================================================% mdlDerivatives% Return the derivatives for the continuous states.%=============================================================================%

Page 94 of 96

Page 95: Simulink and Exercizes Matlab Coursebook

function sys=mdlDerivatives(t,x,u)

COP0=u(6);Tvm=(u(1)+x(1))/2;

Tcm=(u(3)+x(2))/2; COP=COP0*(273.15+Tcm)/(Tcm-Tvm);

Cc=100000;Cv=100000;cv=4200;

cc=4200;

xdot(1)=(1/Cv)*(u(2)*cv*(u(1)-x(1))-(COP-1)*u(5));xdot(2)=(1/Cc)*(u(4)*cc*(u(3)-x(2))+COP*u(5));

sys = [xdot(1); xdot(2)];

% end mdlDerivatives%%=============================================================================% mdlOutputs% Return the block outputs.%=============================================================================%function sys=mdlOutputs(t,x,u)

COP0=u(6);Tvm=(u(1)+x(1))/2;Tcm=(u(3)+x(2))/2;COP=COP0*(273.15+Tcm)/(Tcm-Tvm);

sys = [x(1); x(2); COP;u(5)];

% end mdlOutputs

Page 95 of 96

Page 96: Simulink and Exercizes Matlab Coursebook

SimuLink Model:

Exercise 3: Simulate this model in SimuLink and evaluate the result

Temperaturen

10

T verdamper [oC]

30

T Condensor [oC]

Sum1

T v erdamper oC

F v erdamper kg/s

T condensor oC

F condensor kg/s

E [W]

Tv _uit/Tc_uit/COP

SubsystemScope4

Mux

Mux1

0.05

F verdamper

0.05

F Condersor

Demux

Demux

1000

Constant

COP

Page 96 of 96