25
The University of Sydney Faculty of Engineering ENGG1801 ENGINEERING COMPUTING MATLAB Tutorial Notes Semester 1, 2004

MATLab Tutorial

Embed Size (px)

Citation preview

Page 1: MATLab Tutorial

The University of Sydney

Faculty of Engineering

ENGG1801 ENGINEERING COMPUTING

MATLAB Tutorial Notes

Semester 1, 2004

Page 2: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 2 -

© Faculty of Engineering, University of Sydney, 2004

Page 3: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 3 -

Contents Overview .................................................................................................................................... 4

Assignment Submissions........................................................................................................ 4

Tutorial Weeks 1 & 2 ................................................................................................................. 5

Login ...................................................................................................................................... 5 Using Microsoft Windows ..................................................................................................... 5 MyUni and Email ................................................................................................................... 5 Create a New Folder............................................................................................................... 6 Copying Files and Folders...................................................................................................... 6 Introduction to Excel and Word ............................................................................................. 7

Tutorial Week 3........................................................................................................................ 11

Text Operations in MATLAB .............................................................................................. 11 Algebraic Operations in MATLAB...................................................................................... 11

Tutorial Week 4........................................................................................................................ 13

Description of Problem ........................................................................................................ 13 Program Specifications ........................................................................................................ 13

Tutorial Weeks 5 and 6 ............................................................................................................ 14

Description of Problem ........................................................................................................ 14 Program Specifications ........................................................................................................ 15

Tutorial Weeks 7 & 8 ............................................................................................................... 16

Description of Problem ........................................................................................................ 16 Program Specifications ........................................................................................................ 17

Tutorial Week 9........................................................................................................................ 19

Matrix Manipulations ........................................................................................................... 19 Function Plotting in 2D ........................................................................................................ 20

Tutorial Week 10...................................................................................................................... 21

Figure 1 ................................................................................................................................ 21 Figure 2 ................................................................................................................................ 21

Tutorial Week 11...................................................................................................................... 22

Non-linear Algebraic Equations........................................................................................... 22

Tutorial Weeks 12 and 13 ........................................................................................................ 23

Simultaneous Non-linear Algebraic Equations .................................................................... 23 Solution Method................................................................................................................... 23 Partial Derivatives ................................................................................................................ 24

Page 4: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 4 -

Overview These tutorial notes contain instructions and a set of practice problems for the MATLAB section of the course ENG1801 Engineering Computing. In order to gain a good understanding of engineering computing, especially programming using MATALAB, you should work through these tutorial problems, attempting to stick closely to the proposed schedule. You will need to develop practice in programming in order to pass the quizzes and final exam that will make up the formal assessment in this course.

Assignment Submissions

You are required to submit assignments in only the CAD section of this course. Instructions for submitting the CAD assignments using the SolidWorks package will be provided separately. The tutorial problems in this set of notes will NOT be collected and marked, but you should ensure you can complete them successfully in order to gain the required competence in computing. You should expect several quizzes during the semester. These are designed to test your understanding and competency in programming. Some will form part of your final assessment. Further details will be provided separately.

Page 5: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 5 -

Tutorial Weeks 1 & 2 These first two tutorial sessions are designed to introduce you to the login procedure, the MyUni web site, email, and Microsoft’s Word and Excel programs.

Login

The machines in Computer Access Laboratory form part of a Windows network and require a login procedure. You should have been issued with a user name and password as part of your 1st year enrolment. At the end of each session remember to logout because if you don’t the next person using your machine will have access to all your files. You can logout by simultaneously holding down three keys. They are “Alt” “Ctrl” “Delete”. When you press these three keys a dialog will be displayed. Click the “Logout” command button.

Using Microsoft Windows

Switch on the PC (if necessary) and enter your User Name and your Password in the appropriate dialog box. The first time you do this you will need to enter the password supplied to you at enrolment. You should change this initial password to a secret one of your choosing. If you forget your password you will have to contact the Help Desk, because only system administrators have access to passwords.

To operate software loaded on any PC, select the appropriate Icon (known as a short cut) on the left hand margin of the screen by double clicking with the left mouse button. Alternatively, single click Start at the bottom left hand corner of the screen, then Programs, then the software you want to use, selected by name.

To examine the folders and file structure in any drive of the PC click with the left hand mouse button on the icon: My Computer. This should allow you to investigate the contents of the all drives attached to the computer. You may open a folder, i.e., see the files within a folder, by clicking on the folder icon.

To find any particular folder or file you may: select - Start, Find, then enter the name or part of the name of what you are looking for. You may search all drives or a particular one, e.g.,A:, C: etc.

MyUni and Email

Start up a web browser, such as Microsoft Explorer, by clicking on the appropriate program icon. The browser should open at a home, which is likely to be the University of Sydney home page (http://www.usyd.edu.au).

MyUni is the University of Sydney intranet system (also known as USydNet) and can be accessed by clicking the MyUni icon from the university home page. Alternatively you can enter the address of the MyUni page directly in the address bar in your browser, i.e., http://intranet.usyd.edu.au/student/. To access MyUni you will need to enter your user name and password, which should have been included in the letter confirming your enrolment into this course.

Page 6: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 6 -

MyUni provides you with an email account and access to other useful information such as change of enrolment, exam seat numbers etc. In this tutorial session check your email. You should have received a message from the course co-ordinator. If not, please advise a tutor. In addition, check what facilities and information are available to you and ask a tutor if you require further assistance or explanation.

Create a New Folder

If you need to create a new folder in D: or elsewhere, double click the drive from My Computer, this will open a window for that drive. Right click on the open area of the window for that drive, and a menu like the left hand menu shown on Fig. 1 will open. Select New from that menu, then Folder (as shown). Give the new folder a functional name so that you may recognise its purpose later. Note that folders can contain a mix of other folders and files. Files can belong to a huge range of classes. Windows automatically recognizes many of them.

Figure 1 New folder definition

Copying Files and Folders

To copy files (or folders) from one folder (or drive) to another, open both folders or drives. Click on the file to copy, drag that file across to the other folder. To copy contiguous files, select the first file, hold the Shift key down and select the last file, then drag across as before, indicated on Fig. 2.

To select non-contiguous files, hold the Ctrl key down and click on all the separate files, etc.

You may change names by double clicking slowly (with about a second between clicks) on the file or folder name. A box will appear in which you can type and edit the new file name. Alternatively, click once on the file name using the right button. Then select Rename from the menu that will appear.

Figure 2 Copying files between drives or folders

Page 7: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 7 -

Introduction to Excel and Word

You will need to become familiar with these common and useful software packages. Over the years a surprising amount of power has been added to packages such as these, to the point that it is totally impractical to ignore them.

The spreadsheet Excel

You should work your way through the demonstration of Excel. Some abbreviations and concepts are introduced which will be useful later. Excel has evolved from the earliest spreadsheets, which began as means of carrying out simple mathematical operations on lists or tables of numbers. For example, it can be used to provide simple accounting and to balance budgets. It can include text (to make it readable), mathematical expressions (for a wide range of calculations) and graph functions (to present results comprehensively).

The word processor Word

Word processors are to us what typewriters and off-set printers used to be to previous generations. They are a means of preparing legible, comprehensive text documents. You no longer need a professional type-setter to generate pages that look as if they come from a text book. You can have words, diagrams, photos, tables of numbers, and even equations in a single document, all checked for spelling errors, in single or multiple column layouts.

Exercise in Excel

In this exercise you will establish a simple Excel spreadsheet that tabulates a gas pressure (P) at various temperatures (T) and volumes (V). The gas pressure is calculated using the van der Waals equation:

2Va

bVRTP −−

=

The values of “a” and “b” depend on the gas and the values that we will use in this exercise are for carbon dioxide. R is the gas constant, with units of litre.atm/mol.K. The units of pressure, volume and temperature are atmospheres, litres and degrees K, respectively.

An illustration of the type of spreadsheet that you are required to establish in this exercise is shown in Figure 3. You can create the sheet by starting Microsoft Excel and then following these steps:

• Select cell B3 and type in “R” • Select cell B4 and type in 0.082058 • Select cell C3 and type in “Gas” • Select cell C4 and type in CO2. Highlight the “2” in the formula bar and then use the

menu “Format” then “Cell” to change the “2” to subscript. • Select cell D3 and enter “a” • Select cell D4 and enter 3.59 • Select cell E3 and enter “b” • Select cell E4 and enter 0.0427 • Select cell A6 and enter “Volume” • Enter the following values shown in cells A8:A11, i.e., 0.20, 0.25, 0.30, 0.35

Page 8: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 8 -

• Select cell C6 and enter “Temperature” • Enter the following values across the row in cells B7:D7, i.e. 270, 280, 290 • Select cell B8 and type in the formula:

=($B$4*B$7)/($A8-$E$4)-$D$4/$A8^2

The symbol “^” is typed by pressing the “Shift” then the “6” key. It is used to raise a value to a power and in this example the value in cell A7 is being squared.

This particular formula calculates the value for the pressure when the volume is 0.2 (value in cell A8) and the temperature is 270 degrees (Kelvin) (value in cell B7).

• Select cell B8 and press the right button on the mouse and select “Copy”. Highlight the rectangular block defined by columns B to D and rows 8 to 11. Press the right button on the mouse and select “Paste special” and then select “Formulas”. The pressure values for each combination of volume and temperature should now be displayed. There should be 5 digits after the decimal place.

Highlight the rectangular block where the pressure values are displayed and select the “Format–Cells” menu option. Select the “Number” tab from the dialog box that should be displayed. Select “Number” from the category list and enter “2” in the text box labelled “Decimal places”. Two decimal places may be the default value that is shown and this case no change is required here. Press the “OK” button and the spreadsheet that you have constructed should then be of similar appearance to the one shown in Figure 3.

Figure 3 Excel Spreadsheet

Page 9: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 9 -

7. You may wish to use Excel to draw a graph of these results. An example is indicated in Figure 4. Ask your tutor if you don’t now how to produce something similar.

Behaviour of CO2

0.00

10.00

20.00

30.00

40.00

50.00

60.00

70.00

0.15 0.2 0.25 0.3 0.35 0.4

Volume (litre)

Pres

sure

(atm

)

T=270

T=280

T=290

Figure 4 Example of graphical output

Exercise in Word

In this exercise you are required to produce a Word document that contains the instructions for the Excel exercise described in the previous section. The Word document should reproduce the layout of these instructions as closely as possible. These hints should help you duplicate the layout of the instructions.

1. The main font used for the heading “EXERCISE IN MICROSOFT EXCEL” is “Times New Roman”, 12 point, bold. The font used for the word “EXCEL” is “Arial”, 12 point, bold.

2. The font used for the body of the text is “Times New Roman”, 12 point.

3. The equation has been entered using the Microsoft equation object. You may decide to type the equation in as normal text and then it will be displayed in this way:

P = ( RT / (V – b) ) – ( a / V2 )

4. The bullets are generated by selecting the “Format–Numbers and Bullets” option.

5. The Excel spreadsheet is imported into the Word document using the “Insert-Object” menu option, then selecting the “Create form file” tab and using the “Browse” option to locate the spreadsheet that you have saved from the previous exercise.

Page 10: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 10 -

6. Alternatively, you may copy the relevant cells of the spreadsheet to the clipboard and then past them into Word. To do so, open the spreadsheet, highlight the cells you want to copy, and select the “Copy” option from the “Edit” menu or the appropriate toolbar. Then highlight or open the Word document and select “Edit” and “Paste Special”. You may then choose how you want to paste the spreadsheet into your document, e.g., either as an actual spreadsheet or as an image (in your choice of format). The latter results in a much smaller Word document. The former retains the flexibility of allowing you to open the spreadsheet from within Word, but results in a much larger Word file. A third option is to paste a link to the original Excel file. The advantage of using a link is that if the spreadsheet is updated at any, the spreadsheet table appearing in Word will also be updated whenever the Word file is next opened.

Page 11: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 11 -

Tutorial Week 3 Text Operations in MATLAB

Exercise 1

Enter an input command that prompts the user for the number of trucks that are available on site and assigns the value entered to the variable nTrucks. Enter a number and check the result that is displayed.

Exercise 2

Assign the text “Enter site address” to the variable promptAddress.

Exercise 3

Enter an input command that uses the variable, promptAddress, and assigns the address that is entered to the variable siteAddress.

Exercise 4

Write a series of commands that count the number of lines required to print the address, assuming that a new line must be started when a comma is encountered in the address.

Exercise 5

Use the command fprintf to display the message: “Site Address: ”, and then display the address that you have stored in variable siteAddress on the same line.

Exercise 6

Repeat Exercise 5 using the command disp.

Exercise 7

Use the command fprintf to display the message “Number of trucks currently available: ”, and then display the value stored in variable nTrucks.

Exercise 8

Repeat Exercise 7 using the command disp.

Algebraic Operations in MATLAB

Exercise 1

The density of air (ρ) may be estimated using the ideal gas law as,

RTPM

where M = 29 g/mol and R = 0.08206 litre.atm/mol.K.

Page 12: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 12 -

Use variable names “rho”, “P”, “M”, “R” and “T” and calculate ρ for P = 1.2 atm at T = 24 and 76 deg C.

Exercise 2

The van der Waals equation for the pressure of a gas at various temperatures and volumes can be written as:

2

2

Van

nbVnRTP −−

=

The values of the constants a and b vary for each gas and for oxygen the values are a = 1.36 L2-atm/mol2 and b = 0.0318 L/mol. The constant R = 0.08206 litre.atm/mol.K.

Use variable names that are the same as the symbols used in the equation and calculate the pressure in atmospheres (atm) of 0.18 moles (n = 0.18) of oxygen when V = 0.04 litre, T = 290K.

Exercise 3

Determine the value of the variable “y” from the following expression.

( )( )1

59 )sin(2

+

−+=

xexx

yx

for x = -2.2, 0, 2.8

Page 13: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 13 -

Tutorial Week 4 In this tutorial session you are required to write a program (M-file) that checks whether the values of three parameters entered via the keyboard define a circle, point-circle or an imaginary circle. This exercise requires the use of the commands input and fprintf and the logical construct if. These topics are covered in the lecture notes in the first part of chapter 4.

Description of Problem

The equation of a circle can be written in the following general form:

022 =++++ FEyDxyx

The circle has a centre at (-D/2, -E/2) and radius given by:

2422 FED −+

If the term D2 + E2 – 4F is zero, the graph of the equation represents a point-circle (a circle with zero radius). When D2 + E2 – 4F is negative the radius is imaginary and this situation is sometimes described by saying that the circle is imaginary.

Program Specifications

Read D, E, and F from the keyboard. The program should firstly calculate the value of D2 + E2 – 4F, write out the values of D, E and F and an accompanying message describing whether these values define a circle, point-circle or imaginary circle. If the values correspond to a circle the program should then output the value for the radius and the coordinates of the centre of the circle. If the values correspond to a point-circle the program should then output the coordinates of the centre of the circle. Test the program using three sets of data:

D = 4.35 E = 3.85 F = 8.53

D = 10.0 E = - 4.0 F = - 7.0

D = 8.0 E = 4.0 F = 20.0

Page 14: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 14 -

Tutorial Weeks 5 and 6 This tutorial extends the concepts that were covered in the previous session, i.e., the same commands and logical constructs can be used but the program you are required to write in order to solve this problem will be more complex.

Description of Problem

Structural engineers are required to predict the deformations of beams. A general expression for the central deflection (vertical movement downwards at the centre of the beam) of a simple, uniform beam carrying a concentrated load, W, is given below.

−+−=

333

43218

48 Lb

Lb

La

EIWLδ

The term in the angle brackets “⟨ ⟩” only exists when the contents are positive. These are referred to as Macaulay brackets or Macaulay terms. E is the Young’s modulus of the material used to construct the beam (steel, timber, concrete, etc.) and I is the second moment of area (moment of inertia) of the beam and depends on the cross-sectional shape of the beam (circular, rectangular, etc.)

A general expression for the central deflection of a simple, uniform beam carrying a distributed loading, w, is given below.

−−

−−

−+

−−−−−=

Lb

La

Lb

La

Lb

La

Lb

La

EIwL 231212

214

214

96

4444δ

When the deflections are in the elastic range the principle of superposition can be used and the central deflection of a beam under combined loading can be predicted by summing the two terms.

W

a b

L

w

a b

L

Page 15: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 15 -

Program Specifications

Write a program that calculates the central deflection of a beam under combined loading. The program should read the values of W, w, E, I, L and the values for a and b which specify the positions of the concentrated and distributed loads. Test the program on the beam shown below.

E = 2 x 105 kN/mm2

I = 1 x 108 mm4

0.02 kN/mm 75 kN

1500

2700 4400

9000 mm Not to scale

Page 16: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 16 -

Tutorial Weeks 7 & 8 The program that you write in this tutorial session requires the use of a for loop. The logical construct if-elseif is required and the while loop may be a suitable way of implementing the convergence test. The while and for loops are described in section 4.3 of the lecture notes and iterative solutions and convergence tests are covered in section 4.12 of the lecture notes.

Description of Problem

Computing the value of an integral is a fundamental analytic operation often performed numerically by civil engineering programs. The code computes the “area under the curve” to an acceptable degree of accuracy. This procedure for computing an integral is often called quadrature by numerical analysts. All methods of quadrature require the integrand to be evaluated at discrete points, i.e., the discrete function values f(x1), f(x2), f(x3), ... f(xn) are calculated at the points x1, x2, x3, ... xn.

The trapezoidal method approximates the integral by dividing the area under the curve into N trapeziums or trapezoids, as shown below. Recall that the area of a trapezium is the product of the average length of the two parallel sides and the perpendicular distance by which they are separated. For a region composed of N trapezoids this leads to the following quadrature formula:

( )

+−= +

=+∑ 2

)()( 1

11

iiN

iii

xfxfxxt

The mid-point method (or rectangle rule) divides the area under the curve into a discrete number of rectangles, as illustrated below, and is twice as accurate as the trapezoid method.

If we are to compute ∫b

axf )( we divide the interval [a, b] into N rectangles and calculate the

height of each rectangle as the value of f at the midpoint of the interval f((xi + xi+1)/2). This leads to the quadrature formula:

f(x)

f(x2) f(x3) f(x4) f(x5) f(x1)

x1 x2 x3 x4 x5 x

Page 17: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 17 -

( )

+−= +

=+∑ 2

1

11

iiN

iii

xxfxxr

Examination of ways to reduce the errors in these two methods leads to a simple method that has much greater accuracy. This method is called Simpson’s rule. Multiplying the formula for the rectangle method by two, adding the formula for the trapezoidal method and then dividing the overall result by three leads to Simpson’s rule that states:

( ))()(2)(4)(2)(4)(3

)( 54321 n

b

a

xfxfxfxfxfxfwdxxf ++++++≈∫ KK

where w is the width of each interval which is equal to (b-a)/N.

Program Specifications

Write three programs to evaluate an approximation to the definite integral

∫π

π

2

2

cos dxxex

using Simpson’s method.

Program 1

The program should calculate Simpson’s rule by dividing the interval [π/2, 2π] into eight divisions. The value that the program must calculate is:

( ))()(4)(2)(4)(2)(4)(2)(4)(3 987654321 xfxfxfxfxfxfxfxfxfw

++++++++

The program should not make use of either a FOR loop or an IF statement.

f(x)

x1 x2 x3 x4 x5 x

f((x4+x5)/2)

Page 18: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 18 -

Program 2

Modify the previous program by now employing a FOR loop to sum the nine terms. Note that the first and last terms, f(x1) and f(x9), are multiplied by one. The even numbered terms, i.e. the second, fourth, sixth and eight terms are multiplied by two. The odd numbered terms, i.e. the third, fifth and seventh terms are multiplied by four. You should use an IF statement to decide whether the function value should be multiplied by one, two or four. The “mod” function can be used to determine whether a number is odd or even. The “mod” function returns the signed remainder after division. For example, if the variable “nterm” is even and divided by 2

mod(nterm,2) == 0

Program 3

Modify the previous program by adding an outer loop to existing program. This outer loop determines the number of divisions that the interval is divided into.

The program should firstly divide the interval [π/2, 2π] into two divisions, compute the integral, and then successively double the number of intervals (4, 8, 16, 32, ....) until the value computed differs by less than 10-6 from the correct value which is:

( )2/22

221cos ππ

π

π

eedxxex −=∫

Additionally, the MATLAB function quad can be used to determine the value derived from Simpson’s rule. Note that when the quad function is employed to calculate the integral the function must be specified as ‘exp(x).*cos(x)’.

The program should calculate the correct value from the analytic solution and use this value to determine when the numerical value differs by less than 1.E-06. It should produce a table of the number of intervals, the corresponding computed value of the integral and the difference between the computed and exact value. The first three rows of the table are shown below.

Intervals Integral Difference ========= ======== ==========

2 307.827 4.2486e+001 4 258.524 6.8168e+000 8 264.694 6.4624e-001

Page 19: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 19 -

Tutorial Week 9 Matrix Manipulations

The work covered in this tutorial session is described in the lecture notes starting on page 2-2.

Exercise 1

At the command prompt enter the following matrices:

[ ] [ ]227651 −=A [ ]

−=

23.4

1.356.2

B [ ]

=

135796543254321

10864297531

C [ ]

−=

345302

1443D

Calculate the following and check that the result displayed from your calculation is correct.

Calculate Answers

E = [A] * [B] E = 258.6 ‘E’ is a single valued variable or ‘scalar’.

[F] = [C] * [B] [ ]

−−−−−

=

0.79.63.56.100.9

F

[G] = [A] * [C] [ ] [ ]35328722115589=G

[H] = E * [C]T [H] = 1.0e+003 *

2586.05516.12930.15860.23274.27758.02930.10344.10688.28102.12930.10344.17758.05516.12930.18102.17758.05172.00344.17758.03274.25172.02586.05172.02586.0

[J] = [D] -1 [ ]

−−−

−=

0714.00714.00714.01696.05446.00804.0

1071.03929.01071.0J

[K] = [J] * [D] [ ]

−−−−

=0000.10000.00000.00000.00000.100000.000000.1

K

Page 20: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 20 -

Exercise 2

1) Create a new matrix, [L], by deleting the third row of matrix [C], using the colon operator.

2) Display the 15 digits of each number that form the result of the calculation

[H] = E * [C]T

Exercise 3

Solve the following set of simultaneous equations.

251322

321

321

321

=−+=++−=++

xxxxxxxxx

This equation set can be written as

[C] {x} = {b}

where [C] is the matrix of coefficients, {x} are the unknown values of x1, x2 and x3. The vector {b} stores the values on the right hand side of the equations.

Multiply the matrix of coefficients [C] by the solution {x} and check that the result of this multiplication is the right hand side {b}.

Exercise 4

Enter matrices [A] and [B], where

[ ]

−−

−=

136725312

A [ ]

−−−

−=

932671221543211

B

Calculate [C] = [A] * [B]

Write a series of commands that inspects the value of each element in matrix [C] and returns the total number of values greater than zero, equal to zero and less than zero.

Function Plotting in 2D

Plot the expression,

( )( )1

59 )sin(2

+

−+=

xexx

yx

over the range 1 ≤ x ≤ 5 using a step size of 0.1. Label this plot appropriately.

Page 21: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 21 -

Tutorial Week 10 In this tutorial session you are required to write two programs that each produces a figure generated using low level graphics functions.

Figure 1

The program produces plots of the function z, where

ttz )sin(

= 22 yxt +=

The inputs to the program are the minimum and maximum x and y values and the number of points in each direction at which the function is calculated. Note that the function z is undefined at t = 0, i.e., at x = y = 0. Your program will need to cater for this feature by making appropriate use of the MATLAB function eps.

The specifications for the figure are:

White background.

Z values contoured using function surf.

Colour map is the MATLAB predefined map named “cool”.

Title in bold font that reads “z = sin(t)/t where t = √(x2 + y2)”.

X axis labelled “(x) Coordinate”, Y axis labelled “(y) Coordinate”, Z axis labelled “Z”.

Figure 2

The density of air (ρ) may be estimated using the ideal gas law as,

RTPM

where M = 29 g/mol and R = 0.08206 litre.atm/mol.K.

The specifications for the figure are:

Yellow background. The lines forming the plot are black. Title in bold font that reads “Density of Air ρ (g/litre)”.

X axis labelled “Pressure (atm)”, Y axis labelled “Temperature (K)”, Z axis labelled “ρ = PM / RT”.

ρ values contoured using function mesh covering the ranges 0.5 ≤ P ≤ 2 atm and 20 ≤ T ≤ 100 deg C. Divide the P and T ranges into nine equally spaced divisions. This will result in ten points along each of the P and T ranges.

Page 22: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 22 -

Tutorial Week 11 Non-linear Algebraic Equations

One way to solve a non-linear algebraic equation g(x) = 0 is by rearranging the equation into the form x = h(x) and using the iterative algorithm xi+1 = h(xi). Clearly, this direct substitution method requires an initial starting guess (x0).

This approach is commonly used in flowsheeting packages to solve the material and energy balance equations for processes that involve recycle streams. However, this method can be slow to converge and for some rearrangements (note that it is often possible to come up with a number of alternative x = h(x) expressions) diverges even with a good starting guess.

For flow through a “smooth” pipe at Reynolds numbers (Re) above 4000, the friction factor f (used to calculate pressure drop through the pipe) is given by the formula:

( ) 8.0Reln86.01−= f

f

Note that once Re is given, the above is an implicit equation in f (that is, it cannot be rearranged into a version that can be solved directly for f).

Note also that this equation can be rearranged into the following "direct substitution" form:

2)8.0)ln(Re86.0(1

−=

ff

Using a while loop, write a Matlab program that solves the above equation for the friction factor for a given Reynolds number. Your program should check that both convergence to the required accuracy (i.e. successive estimates of f should differ by less than 10-5) has been attained and that the maximum number of iterations (set at 10) has not been exceeded.

Note that all iterative methods require an initial ‘guess’ at the solution. Estimates taken from a Moody chart are that f ≅ 0.03 at Re = 104 and f ≅ 0.012 at Re = 106.

The program must produce a tabulation of the iteration number, the corresponding computed value of the friction factor and the difference between this value and the value computed in the previous iteration. An example is shown below.

Reynolds number > 10000 Intial "guess" for friction factor > .03

Iteration Friction Factor Difference

1 0.0317 -

2 0.0315 2.7232e-004

3 0.0315 4.1405e-005

4 0.0315 6.3239e-006

Page 23: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 23 -

Tutorial Weeks 12 and 13 Simultaneous Non-linear Algebraic Equations

Example 10.3-2 in Felder and Rousseau (see pages 524-526) discusses the solution of a simple (ethane dehydrogenation) reactor-separator flowsheet. Both the reactions of interest,

C2H6 ⇔ C2H4 + H2 (1)

C2H6 ⇔ C2H2 + 2H2 (2)

are assumed to reach equilibrium within the reactor. The extent of each reaction (defined as the percentage of the ethane entering the reactor that undergoes a particular reaction) are denoted by ξ1 and ξ2, respectively.

On page 526, a calculation scheme is given for this process simulation – the first step of which is to solve the following two nonlinear equations for ξ1 and ξ2:

f1(ξ1, ξ2) = ξ1 (ξ1 + 2ξ2) – 3.75 (100 – ξ1 – ξ2) (100 + ξ1 + 2ξ2) = 0 (3)

f2(ξ1, ξ2) = ξ2 (ξ1 + 2ξ2)2 – 0.135 (100 – ξ1 – ξ2) (100 + ξ1 + 2ξ2)2 = 0 (4)

In this tutorial you write a MATLAB script file that solves these two non-linear simultaneous equations. The method you should use to solve these equations is described in the following section.

Solution Method

If an approximation is made to the solution ( )02

01 ,ξξ then the solution (ξ1, ξ2 ) is

10

11 ξξξ ∆+= (5)

2022 ξξξ ∆+= (6)

and

( ) ( ) 22

11

02

0112

021

011 ,, ξ

ξξ

ξξξξξξξ ∆

∂∂

+∆∂∂

+≈∆+∆+ffff (7)

( ) ( ) 22

11

02

0122

021

012 ,, ξ

ξξ

ξξξξξξξ ∆

∂∂

+∆∂∂

+≈∆+∆+ffff (8)

These two equations can be rewritten as:

( ) 22

11

02

011 ,0 ξ

ξξ

ξξξ ∆

∂∂

+∆∂∂

+≈fff (9)

( ) 22

11

02

012 ,0 ξ

ξξ

ξξξ ∆

∂∂

+∆∂∂

+≈fff (10)

Page 24: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 24 -

or

( ) 22

11

02

011 , ξ

ξξ

ξξξ ∆

∂∂

+∆∂∂

≈−fff (11)

( ) 22

11

02

012 , ξ

ξξ

ξξξ ∆

∂∂

+∆∂∂

≈−fff (12)

The solution to these as two simultaneous equations with the unknowns ∆ξ1 and ∆ξ2 requires an iterative procedure and the steps that must be followed are:

[1] Make an assumption for ( )02

01 ,ξξ . Reasonable starting values for ξ1 and ξ2 are 50%

and 10%, respectively.

[2] Solve equations 11 and 12 for ∆ξ1 and ∆ξ2

[3] Compute new estimates for ( )12

11 ,ξξ

10

111 ξξξ ∆+= (13)

202

12 ξξξ ∆+= (14)

[4] Repeat steps 2 and 3 until the function values (equations 3 and 4) are less than .01%.

The output from your program must include the table shown below. You should check that your program correctly calculates the values shown for the first two iterations.

Iteration xi-1 xi-2 f1 f2

1 88.66 6.61 5.45e+003 42506.82

2 83.12 6.27 1.71e+002 2593.23

.

.

Partial Derivatives

The partial derivatives of these two functions are:

211

1 25.135.9 ξξξ

+=∂∂f (15)

212

1 1537525.13 ξξξ

+−=∂∂f (16)

( ) ( ) ( )( )21212

212121

2 2100100270.02100135.22 ξξξξξξξξξξ

++−−−++++=∂∂f (17)

Page 25: MATLab Tutorial

ENGG1801 Engineering Computing Tutorial Notes

- 25 -

( ) ( ) ( ) ( )( )

)18(

2100100540.02100135.0242 21212

212122

212

2 ξξξξξξξξξξξξ

++−−−++++++=∂∂f

There are numerous “toolboxes” that can be licensed for use with MATLAB. There is a numerical analysis toolbox that includes a function named fsolve, that can be used to solve simultaneous non-linear equations. If your program works correctly then you have written the equivalent of this toolbox function.

Reference

Felder, R.M. and Rousseau, R.W. Elementary principles of chemical processes, 675pp, 3rd Edition, John Wiley and Sons, 2000.