Вы находитесь на странице: 1из 9

CE2602/CE2603 Sustainable Construction/Infrastructure and Professional Skills

Assignment for MATLAB Programming

References: All information required for completing this assignment can be found in Lecture Notes
(Blackboard). It is advisable to complete all tasks in all 3 MATLAB workshops before you start the
assignment tasks. Many good books can be found in Brunel Library for more information on MATLAB
programming,e.g.anyofthefollowingbookswillgiveyouagoodintroductorytutorial.
A.Gilat,MATLAB:AnIntroductionwithApplications,JohnWiley&Sons;4thEd.,2011
S.Chapman,J.,MATLABProgrammingforEngineers,NelsonEngineering;4thEd.,2007
H.Moore,MATLABforEngineers,PearsonEducation;3rdEdition,2011

There are vast amount of information available on internet about MATLAB including good tutorials and
lecture notes. To find information for a specific topic, just Google MATLAB specific topic, e.g. Google
MATLABinterpretationcanfindtheinformationaboutdatainterpretationwithMATLAB.

MATLABTips/Tricks
Togetinfoandexamplesonhowtouseafunction/command,usedoc,e.g.>>doc interp1
ToreturntopreviouslytypedcommandsinCommandWindow,youcanusearrowupkey.
UpperorLowCase:MATLABiscasesensitive:allfunctionsmustbeinlowcases,butvariablescan
be in low cases, upper cases or mixed. Rules for function/variable names see Lecture Notes (LN)
Page(P)5Slide(S)18.
LocationtoSaveMATLABprogramordata:Youcanchangeworkdirectory(folder)toanyother
directory(folder)suchasH:\mywork.Seetopleftimmediatelyabovecommandwindow.
TocopyafigureintoaworddocumentusecopyfigureunderEdit.Youcanchangefigurecopy
optionsandfigurepropertiesunderEdit.

SubmissionDeadline: Week23Thursday26/02/2015,4PM,ConfirmwithSPO

WhattoSubmit:
ThereporttogetherwithallMATLABprogramsonaCD.

RequirementforPrograms
Alltasksineachproblemshouldbesolvedbyoneprograms(scriptfile)togetherwithfunctionfiles
ifrequired.
Use ; to suppress all results (especially intermittent results) from MATLAB command window.
However, all final results should be presented on the command window very clearly using
formattedtexts(fprintf( ),LectureNotes(LN)Page(P)28Slides(S)110112).
Allplotsshouldhavetitlesandlabelsforallaxes.
To make a MATLAB program readable for other program users and yourself, it is important to
includesomecommentsandverybriefexplanationthroughouttheprogram.InMATLAB%isused
toaddcomments.Onanylineofprogram,anythingafter%willbeignoredwhen the programis
executed.Thefirstcontiguouscommentontheprogrambecomesthescript'shelpfile.Itisagood
idea to identify main and important variables used in the beginning of program. Please add
sufficient comments when you write the program, this will help you to avoid wasting time later
when you need to debug the program. However, it is not necessary to comment every line of
program.Onlycommentonimportantlines.
The program should only require the minimum intervention by users. If the user is required to
enteranyinformation(e.g.entersomenumbers),someclearandselfexplanatorypromptsshould
bepresentedonthecommandwindow.

RequirementsforReport(CheckSampleAssignmentReporttofindwhatarerequired.)
Itisdesirabletoincludesomeverybriefexplanationsfortheprogramdevelopment,forexample,
toderivemathematicalequationswhichareusedintheprogram,touseaflowcharttoexplainthe

programflowetc.
Allfinalresultsandplotsforeachtaskshouldbepresentedinthereport.Whenappropriate,some
discussionsonresultsshouldbeincluded.
All programs (MATLAB codes) should be included in the report with some annotations which
explainthefunctionofalineofcode(ifitisimportant)orablockofcodes.Donotexplainevery
codeline,onlyexplainaccordingtotasksorsubtasks.
Maximumpagenumber:14.

RequirementsforsubmittingprogramsonCD
AllprogramsshouldbeprovidedonaCDwhichissubmittedwiththereport.Beforeyouburnfiles
totheCD,itisadvisabletocreateafolderonthecomputerandputallfilesinthisfolderandtest
runthemwithinMATLAB.
Forthereportmarking,allprograms(scriptfiles)willbetestedtochecktheircorrectness.

MarkingCriteria:Allproblemswillbemarkedaccordingtothefollowingmarkingcriteria.
[80100]:Inadditionto[7079],theadditionalmarkswillbeawardedtoqualityofMATLAB
programandexplanations,forexample,efficientprogramcodes,properinprogram
explanations/comments.
[7079]:TheMATLABprogramsarecorrectandcorrectresultsareproduced(Theprograms
suppliedonCDwillbetested).Programcodesarepresentedinthereportwithproper
annotationstoexplainthefunctionsoftheprogram.Resultsarepresentedclearlyonthe
reportandtheresultsarediscussed(ifrequired).
[6069]:TheMATLABprogramsrelatedtomajorityoftasksarecorrectandcorrectresultsare
producedformajoritytasks.(TheprogramssuppliedonCDwillbetested).Programcodes
arepresentedinthereportwithsomeexplanationsandcomments.Resultsarepresented
clearlyonthereportandtheresultsarediscussed(ifrequired).
[5059]:TheMATLABprogramsrelatedtooverhalfoftasksarecorrectandcorrectresultsare
producedforoverhalfoftasks.(TheprogramssuppliedonCDwillbetested).Program
codesarepresentedinthereportclearly.Producedresultsarepresentedonthereportand
somediscussionsarepresented(ifrequired).
[4049]:TheMATLABprogramsrelatedto1/3oftasksarecorrectandcorrectresultsareproduced
forover1/3oftasks.(TheprogramssuppliedonCDwillbetested).Programcodesare
presentedinthereport.Someresultsarepresented.
[3039]:Theprogramsfailtorun,howeversomegoodeffortshavebeenmadetocompleteall
tasks.(TheprogramssuppliedonCDwillbetested).Someprogramcodesarepresentedin
thereport.
[029]:Asuitablemarkswillbegivenbasedontheprogramsproducedandtheeffortmade.

Thefinalmarkwillbecalculatedaccordingtothefollowingweightingfactors.
DiscretionaryMark(reportpresentation,program
P1
P2
P3
P4
P5
P6
P7
correctnessandefficiency.
10% 15% 20% 20% 10% 10%
5%
10%

Plagiarism will be dealt with very seriously. In some cases, to clarify the report and
associatedprograms,somestudentsmayberandomlyselectedtoattendanoralassessment
todemonstratecertainMATLABprogrammingtasksoncomputers.
Assignment Marking & Feedback: Due to amount of work involved in marking each
assignmentandthenumberofassignmentstobemarked,itisunlikelythefeedbackwillbe
given in three weeks time. However, this will not affect your revision because MATLAB
programmingisonlyassessedbythisassignment

Assignment Problems
P1:

MATLAB Basics: Generate and Save Data, 2-D plots. (Estimate time required 20
minutes)
AlltasksforP1shouldbecompletedinasingleMATLABprogram(scriptfile).

Write a MATLAB program (script file) to complete the following tasks.


P1.1

To distinguish a students work from other students, a unique number stuid which is
**
related to each students id must be generated according to the following MATLAB codes .
Once generated, this number is fixed and should be used in all following problems when it is
required.

RandStream.setGlobalStream(RandStream('mt19937ar','seed',0506833))
stuid=rand(1);
replaceitwithyourstudentid

P1.2

In a wind tunnel study of dense gas dispersion in a neutral boundary layer over a rough
z2
surface, the Gaussian function c = exp 2 is used to model relationship amongst the
2s
average plume concentration ratio (c), height (z) and vertical plume speed (s).
1) Generate 251 equally spaced data points within the interval [-6.9, 6.9] for z. (Ref
Workshop3_W3P1).
2) Generate 251 experiment noise data (mnoise) which follow a normal distribution with
mean 0 and standard deviation of 0.026 (For generating random noise with the command
randn( ),seeW3P3(1).)
3) Calculate values for c for all z according to the following experiment equation.
z2
s = 2.1(1 + 0.55stuid )
c = exp 2 + mnoise
2s
4) Plot c vs z.

P1.3

Save variables stuid, s, z and c in a MATLAB data file and this will be used in following
part of the assignment. (Forsaving/loadingdatain/fromadatafile,seeLNP6,S22,S23.)

P2:

Use MATLAB to solve linear simultaneous equations (Estimate time required,


30 minutes.)

F1
A truss is loaded as show in Fig.P2, the forces applied to the truss
are F1 = 22(1 + 0.2stuid ) and F1 = 45(1 + 0.9stuid ) . Using the
following set of equations, solve for the 10 unknown force variables,
Fab, Fbc, Fad, Fbd, Fcd, Fde, Fce, Ax, Ay and Ey.
Ax + Fad = 0
F2 +Fbc + (3/5)Fbd = 0
Fbc + (3/5)Fce = 0
Fad + Fde + (3/5)Fbd = 0
Fde + (3/5)Fce = 0

-Ay - Fab = 0
-Fab (4/5)Fbd = 0
-F1 Fcd (4/5)Fce = 0
-Fcd- (4/5)Fbd = 0
-Ey - (4/5)Fce = 0

F2

Fbc
Fbd

Ax

4m F
ab
A
3m
Ay

C
Fce
Fcd
3m

Fad D Fde
Figure P2

**

If you use MATLAB version older than 2011b, the set seed command should be
RandStream.setDefaultStream(RandStream('mt19937ar','seed',0506833))

Ey
E

The equations need to be converted into matrix format first. (See example in LN
P14,S5455.)
ThevariablestuidshouldbeloadedfromthedatafilesavedinP1.
ThisproblemshouldbecompletedinasingleMATLABprogram(scriptfile).
1
*

*
Startwiththisstructure *

*
*

*
*

P3:

0 0 0

0 0 0 1

* * *
* * * *
1 0 3/5 0 0 0 0
* * *

* * * *

* * *
* * *

* * * *
* * * *

* * *
* * *

* * * *
* * * *

* * *

* * * *

* * *

* * * *

0 0 Fab 0

* * Fbc *
0 0 Fad F2

* * Fbd *
* * Fce *
=

* * Fde *
* * Fce *


* * Ax *
* * Ay *

* * E y *

Use MATLAB to solve constraint optimization problem (Estimate time required


30 minutes,)

The optimal design of a three-bar truss shown in Fig.P3 is considered. The vertical deflection of its
loaded joint gives the objective function to be minimized.
f =

Ph
1
E x1 + 2 x2

where P = 25(1 + 0.1stuid ) , E = 2 and h = 2 .

where the cross-sectional areas of its members are A1 = x1 and A2 = x2 ; here x1 and x2 are the design
variables. Load P is applied in the direction shown in Fig.P3.
The constraints are the applicable stresses on the three members and lower and upper bounds on the
design variables as follows.
x2 + 2 x1
17.5 (maximum permissible stress in tension)
2 x12 + 2 x1 x2
1
P
17.5(1 + 0.1stuid ) (maximum permissible stress in tension)
x1 + 2 x2
x2
P
1.2 (maximum permissible stress in compression)
2 x12 + 2 x1 x2
0.2 x1 6(1 + 0.2 stuid )
0.2(1 0.1stuid ) x2 6
P

Use fmincon() to obtain the optimized value for the cross-sectional areas and the minimum
vertical deflection.

SeeexampleinLNP3839,S150155.
To solve a constraint optimization problem, you need to define TWO functions, one
functionforthecost(objective),anotherfordescribingconstraints.Bothfunctionscan
be defined as in program anonymous functions or by separate function files. You
mustconvertallconstraintstothestandardformatsothattheycanbedescribed.
Allcommandsshouldbeinscriptor/andfunctionfiles.
ThevariablestuidshouldbeloadedfromthedatafilesavedinP1.

p=

q=

Figure P3
P4:

fA1 A2 Le
2 DaL( A1 + A2 )

ga ( A1 + A2 )
LA1 A2

Figure P5

Curve Fitting/Model Identification: find a suitable formula/model to fit


experiment data. (Estimate time required 40 minutes)

Load experiment data set (z, c vectors (z(1), c(1)), (z(2), c(2)), , (z(251), c(251))) saved in P1.3.
Note that only z and c should be loaded, nothing else!!! These data will be used to identify the
z2
model which describes the relationship between c and z, i.e. c = exp 2 . More specifically, the
2s
model identification is to identify the parameter s (assumed unknown in here) in the model
equation so that this equation fits experiment data.
P4.1

Model Identification Method 1: The least square method can be used to find the model
z2
parameter s so that the model ( c = exp 2 ) fit experiment data (z, c vectors.
2s

LeastCurveFittingMethod:
For a linear equation y=ax and experiment data set (x(1), y(1)), (x(2), y(2)), , (x(N), y(N)), the least
squareestimationforaisgivenby
N

a =

x(k ) y (k )
k =1
N

( x(k ))

x(1) y (1) + x(2) y (2) + " + x( N ) y ( N )


( x(1)) 2 + ( x(2)) 2 + " + ( x( N )) 2

sum( x.* y ) / sum( x. ^ 2)

k =1

UsetheLeastCurveFittingMethodtoIdentifyNonlinearModelParameters:
As discussed above, the least square method is developed for linear model equations. Nonlinear
equationssuchastheonewehaveinheremustbefirstconvertedintolinearequations.

z2
1
=
c exp 2 ln(c) = 2 z 2
2s
2s

Bydefining y = ln(c),

y = ax
Thenonlinearequationhasbeenconvertedtothelinearequation
Theleastsquaremethodcanthenbeusedtoestimatetheparametera.Onceaisestimated,the
correspondingestimateforscanbedetermined(s1).

x = z 2 and a =

2s 2

Programsteps:
(1)Loadcandz
(2)Calculatexandyaccordingtothedefinitionabove.
In theory, the values for c should all be positive. However, some values generated in
Problem P1.2 may become negative because measurement noise was added. This
maycauseproblemforthecalculationofln(c).Thisproblemcanbeovercomebyusing
ln(|c|)insteadofln(c).log(abs(c))inMATLAB.

(3)Findtheestimationofausingtheleastsquareformula.Forthecalculationofsum,see
Workshop3W3P3.
(4)Determinesusinga.(usethevariables1tostorethevalueofsinordertodifferentiate
withthefollowingpart).

P4.2

Model Identification Method 2: Due to a special property of the Gaussian function, the
following relation can be used to find the value of s using data loaded.

2 1
z2
s = z f ( z )dz = z
exp 2 dz

2
2
+
z2
1
1
2
=
z exp 2 dz =


2
2
2

1 + 2
s3 =
z c dz
2
2

( z c ) dz
+

( )

Use trapz( ) command to calculate the integration, the estimate (s2) of the parameter s
is then determined. (Theintegrationrangefromto+simplymeansthattheintegrationisfor
thewholerangeofz.)
P4.3

Model Identification Method 3: The model identification problem is an optimization


problem which is to find the optimal parameters to make the sum of square of prediction
errors minimum. Use a MATLABs optimization command (e.g. fminsearch) to find
the parameter s to minimize the following cost function.

z (k ) 2
J = c(k ) exp

2
k =1
2s
251

J is a function of s.

The estimate (s3) of the parameter s is determined by minimizing the above cost function.
(ForminimizationseeWorkshop2W2P1&W2P2,LNP34P35,S135137).
P4.4

To check the goodness of the models identified, the identified parameters (s1, s2, and s3) will
be used to determine the predicted model outputs according to the following equations.
z2
c1 = exp 2
2s1

z2
c2 = exp 2
2 s2

z2
c3 = exp 2
2 s3

Use subplot command to plot four graphs (c versus z, c1 versus z, c2 versus z, c3 versus z)
on the same figure window. (ForusingsubplotseeLNP21,S8182.)

P5:

Solving Differential Equation and Using Data Interpretation (Estimate time


required 45 minutes)

The oscillations caused by a suddenly released fluid from a height difference Z that separates the
fluid levels in two rectangular prismatic reservoirs connected by a long pipeline of length L, as
shown in Fig. P5 can be determined from

d 2 Z (t )
dZ (t ) dZ (t )
+ signum
p
+ qZ (t ) = 0
2
dt
dt dt
p = 0.375m 1
q = 0.00074 s 2
P5.1

Use a differential equation solver in MATLAB (i.e. ode45, ode23 or ode15s) to solve
dZ (0)
the above equation for the time interval [0, 300] and initial conditions
= 0m/s and
dt
x>0
1
dZ (t )

Z (0) = 20m . Plot Z (t ) and


against time t. (Note that signum( x) = 0 x = 0 and
dt
1 x < 0

this is implemented in MATLAB by sign(x) )


ForsolvinghigherorderdifferentialequationsseeWorkshop2W2P4andLNP44,S173174.

P5.2

dZ (0)
= 0m/s and Z (0) = Z n , determine the value of the first
dt
occurrence of tn for which Z (tn ) = 0 when Z n = 5m,10m,15m," 50m . Plot tn vs Zn. (The
value of tn can be found in many ways. The easiest way is to simulate (solve) the
differential equation for a longer period time and then use interp1 to find tn for
Z (tn ) = 0 .)
Set the initial conditions as

20

Basically,youneedtorepeattheworkofP5.1withallinitial
conditionsZn=5,10,15,,50.Todothisrepeatedaction,you
needtouseloopoperation,for-end looporwhile-end
loop (LN4853).Themaintaskforthispartistofindthetime
oftnforwhenZ(tn)=0(seegraphontheright).Thiscanbedone
bythefindcommand(LNP53,S212213)andtheinterpretation
(LNP54,S214216).

10

tn

Method1:Veryroughapproximation
Pindex=find(Z<0);
t0=(t(Pindex(1))+t(Pindex(1)-1))/2;
Method2:Approximatewithmoredatapoints
Pindex=find(Z<0);
zz=Z(Pindex(1)-3:Pindex(1)+3);
tt=t(Pindex(1)-3:Pindex(1)+3);
t0=interp1(zz,tt,0);

when Z(tn)=0

5
0
-5

ItcanbeseenthatnodatapointatexactlyZ(t)=0,
sothatsomeapproximationsmustbemade.We
justneedtofindthefirstdatapointwhenZ(t)<0
andthelastdatapointwhenZ(t)>0.

Position Z(t)
Velocity dZ(t)/dt

15

50

100

150

200

250

300

20
Position Z(t)

1
t0 (t1 + t2 )
2

15

10

Last data point


for Z(t)>0
No data point at
exactly Z(t)=0
1st data point
for Z(t)<0

-5

t2 t
1
t0

50

100

150
Time (seconds)

200

250

300

P6:

MATLAB loops, conditional and logic operations, formatted text, find


solutions for nonlinear equations (Maximum expected time 45 minutes)

The bisection method can be used to solve a single variable equation when a unique solution exists
within an interval [ xL , xR ] . See Fig.P6.
y = f ( x) = 0

When f ( xL ) and f ( xR ) have opposite signs (i.e. f ( xL ) f ( xR ) < 0 ), a solution exists within interval
[ xL , xR ] . The middle point xC can be chosen as a trail solution. It is unlikely that this trail solution
is the true solution i.e. f ( xC ) 0 . However, the solution interval can be narrowed as either [ xL , xC ]
or [ xC , xR ] (depends on the signs of f ( xL ), f ( xC ), f ( xR ) ). Repeat this process until the interval is
sufficiently small or the solution has been found.

y
f(xR)

f(xL)f(xR)<0

xL + x R
2
or = xL + 0.5( xR xL )
xC =

y=f(x)

f(xC)
xL

xC
f(xL)

xR

solution

Figure P6
The following equation which relates the thickness of an airfoil in aircraft wing designs is known to
have a solution in the interval of [0, 1].
y = f ( x) = 2.83x3 3.45 x 2 + 1.55 x (0.15 + 0.15stuid ) = 0
Write a MATLAB program (script file) to complete the following Tasks. The parameter stuid
should be loaded from the data saved in P1.3. (Only load stuid, nothing else).
P3.1

Use the command fplot( ) or plot( ) to plot this function (x in the range of [0, 1]).

P3.2

Find the solution using the Bisection method. The iteration will be terminated when
| xR xL | 0.00001 (the solution interval is sufficiently small) or | f ( xC ) | 0.00001 (a
solution found) or the iteration number reaches to 40. The program should be able to
generate and present the following information.

Note 1:Forprogrammingidea,especiallythewaysofpresentedinformationonthescreenusing
formattedtext,pleaseseeexampleinLNP59,S235.
Note2:MoredetaileddescriptionandtheprogramexampleforBisectionmethodcanbefoundin
https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/10RootFinding/bisection/
Note3:Ifyouwriteafunctionmfiletodefinethefunction,youneedtodeclarestuidasaglobal
variablebyaddingalineglobal stuidinthebeginningofyourmainscriptfileandalsointhe
functionfileimmediately afterfunctionstatement.Afunction mfileisindependentof MATLAB's
mainworkspace(includingcommandwindow&scriptfile).

P6.3

To improve the Bisection method, the golden ratio is used to determine the middle point.
Find the solution using the following middle point. The tabular information same as P3.2
are also required for this task.

3 5
( xR xL ) if
xL +

2
xC =
x + 5 1 ( x x ) if
R
L
L
2

| f ( xL ) |<| f ( xR ) |

(
| f ( xL ) |>| f ( xR ) |

5 1
the golden ratio).
2

P6.4

Use the MATLABs build-in function fzero to find the solution and compare it with
results obtained in P4.2 and P4.3.

P7

MATLAB program branches (Estimate time required 20 minutes, example see


Workshop3W3P4 )

Write a MATLAB program to call all programs written for all problems for this assignment. When
this program is run, a selection menu similar to the following one should be presented.
Select Problem to solve:
1: Problem P1
2: Problem P2

6: Problem 6

Once the selection is made, the relevant program should be executed to solve the problem selected.
(Use MATLAB command switch-case-end). The program should be able to return to the
selection menu before all problems have been solved.
9

Вам также может понравиться