157
ENG3103 Engineering Problem Solving 3 Faculty of Engineering and Surveying MATLAB Short Course Written by: KA Moore Faculty of Engineering and Surveying The University of Southern Queensland

MATLAB Short Course

Embed Size (px)

Citation preview

Page 1: MATLAB Short Course

ENG3103Engineering Problem Solving 3

Faculty of Engineering and Surveying

MATLAB Short Course

Written by:KA MooreFaculty of Engineering and SurveyingThe University of Southern Queensland

Page 2: MATLAB Short Course

Published by

University of Southern QueenslandToowoomba, Queensland 4350Australia

http://www.usq.edu.au

© University of Southern Queensland, 2004.2

Copyrighted materials reproduced herein are used under the provisions of the Copyright Act 1968 as amended, or as aresult of application to the copyright owner.

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any meanselectronic, mechanical, photocopying, recording or otherwise without prior permission.

Produced using LATEX 2� by KA Moore in the USQ style.

Page 3: MATLAB Short Course

Tableof Contents

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (v)

1 The MATLAB Workspace 1

1.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.2 TheMATLAB Desktop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.3 BasicCommandsandDataTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.4 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

1.5 CommonMATLAB FunctionsandRelationalOperators . . . . . . . . . . . . . . . . . 10

1.6 PlottingandInput/OutputOperations. . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

1.7 Problem-SolvingTechniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

SelfAssessmentQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

TutorialProblems. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Solutionsto SelfAssessmentQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . 20

(i)

Page 4: MATLAB Short Course

2 Array and Matrix Operations 21

2.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2.2 CreatingArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2.3 VectorandMatrix Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.4 Polynomials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

SelfAssessmentQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

TutorialProblems. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

Solutionsto SelfAssessmentQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . 32

3 Files,Functions and Data Structur es 33

3.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3.2 DataImport andExport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3.3 BasicI/O andMathematicalFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

3.4 User-DefinedFunctions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

3.5 CellsandStructures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

SelfAssessmentQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

TutorialProblems. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

Solutionsto SelfAssessmentQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . 45

(ii)

Page 5: MATLAB Short Course

4 Programming with MATLAB 47

4.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

4.2 RelationalandLogical Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

4.3 ConditionalStatements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

4.4 ProgramDesignandDocumentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

4.5 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

4.6 Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

SelfAssessmentQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

TutorialProblems. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

Solutionsto SelfAssessmentQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . 62

5 Plotting and Model Building 63

5.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

5.2 PlottingFunctions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

5.3 FunctionDiscovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

5.4 3D PlottingandGraphicsOutput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

SelfAssessmentQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

TutorialProblems. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

Solutionsto SelfAssessmentQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . 76

Reference 77

Appendix A Model Solutionsfor Self-Testsand Tutorial Problems 79

A.1 TheMATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

A.2 Array andMatrix Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

A.3 Files,FunctionsandDataStructures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

A.4 Programmingwith MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

A.5 PlottingandModelBuilding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

(iii)

Page 6: MATLAB Short Course

(iv)

Page 7: MATLAB Short Course

Introduction

Intr oduction

The ability to create,implementandinterpretsometimescomplex computerprogramshasbecomeanalmostmandatoryrequirementfor the graduateengineerin all disciplines. Thesedaysgraduatesareexpectedby industry to be able to devise appropriatecomputersolutionsto both standardand non-standardengineeringproblems,or, wherecommerciallyavailablesoftwaredoesexist, to beableto adaptor modify existing computermodelsfor particularnon-standardapplications.

Theobjectivesof thiscoursearetwofold. Firstly it is intendedto provideyouwith someinitial exposureto, andsomehands-onexperiencewith ahigh level computerprogramminglanguagein orderto developsomebasiccompetenciesin workingwithin aprogrammingenvironment,andin creatingcomputercodeto implementsolutionsto typical standardandnon-standardengineeringproblems.Secondlyit aimstodevelopskills in engineeringproblem-solvingwithin thecontext of computerprogramming.As we willseelaterin thiscourse,problem-solvingis aprocesswhichcanbegenerallydescribedasaseriesof stepstheengineerfollows in orderto implementpracticalsolutions:

(i) Understandtheproblem.

(ii) Simplify theproblemasmuchaspossible.

(iii) Collectthenecessarydata/informationrequiredto formulateasolution.

(iv) Formulateanalgorithmto implementasolution.

(v) Implementthesolution.

(vi) Performa ’reality check’on theanswers.

Thisproblem-solvingmethodologywill betheprimaryfocusthroughoutthis course.

Thelanguagechosenasaplatformthroughwhichto imparttheseskills is MATLAB, althoughthechoiceof languageis not particularly importantin termsof the degreeto which the necessaryprogrammingskills can be developed. Most of the high level languagesusedin engineeringsuchas C, C++ andFORTRAN all usesimilar datatypessuchassingleanddoubleprecisionfloats,long andshortintegers,arraysandstructures,andsuchprogrammingconstructsasconditionalstatements,loops,functionsandsubroutines,so that having gainedmasteryin oneparticularlanguageit is not difficult for the studentto masteranother. Theskills you gain in this andin subsequentrelatedsubjectswill alsogive you theconfidenceto implementsolutionsin languagesotherthanMATLAB.

MATLAB is morethanjustaprogramminglanguage;it is aprogrammingenvironment. In contrastwithotherhigh level languages,the MATLAB programmingenvironmentallows interactiveprogrammingandfurthermoreit doesnot requireprior compilationof thecomputercodein orderto implementit. It iswidely usedin universitiesthroughouttheworld andindicationsarethat it is fastbecominganindustrystandardin Australia. It operatesundera Windows-basedenvironmentandthe languageitself is very

(v)

Page 8: MATLAB Short Course

similar to C, althoughtherearemany additionalconstructsandbuilt-in functionswhichmake theMAT-LAB languagesuperiorto standardC in many respects.Although the ideaof interactive programmingis extremelyusefulasa learningtool, mostengineeringsolutionsrequiremuchmore than just a fewcommand-lineinstructions,andwe will focusmoreon developmentof suitableM files to implementproblemsolutions.An M file is simply a setof MATLAB instructionscontainedwithin anASCII1 textfile, andhasthesamepurposeas sourcecodein moretraditionalhigh level programminglanguages.

TheResourceBook for this subjectis theprescribedtext:

Palm,W. J.(2001),Introductionto MATLAB6 for Engineers, McGraw-Hill .

The materialin this booklet is intendedto complementthe text, providing additionalexplanationandemphasiswhererequired.Thetext includesprogressively-staged self-testquestionswhich aregenerallyof the short-answertype aswell astutorial problemsat the endof eachchapter. Answersto someofthe text-basedself-testquestionsareprovided in the text with the question,andthosefor someof thetext-basedtutorial problemsareprovidedin thefinal pages(pp.590-592)of thetext.

Thisbookletprovidesadditionalself-assessmentquestionsin multiple choiceform designedto improveyour comprehensionof someof themoreimportantaspectsof thematerial.Answersto thesemultiplechoicequestionsareprovided at theendof eachModuleof this booklet. Thesettutorial problemsarelistedat theendof eachModule. Most of theseproblemsaretaken directly from the text. Answerstothesetutorial problemsareprovided eitherin the final pagesof the text, or if no answersaregiven inthetext, they areincludedwith theproblemat theendof eachModule.Model solutionsfor someof theself-testandtutorialproblemsaregivenin AppendixA of thisbooklet.Rememberthatmistakesarepartof the learningprocessandmoststudentslearnmoreeffectively from the mistakes they make. Don’tdeprive yourselfof that learningexperienceby consultingthemodelsolutionsbeforeyou have madeanhonestattemptat theself-testor tutorial problem.

This bookletwill cover materialmostly from the first five chaptersof the text namelythe MATLABworkspace,datatypes,programmingconstructs,functionsandM files,reading/writingdata,curvefittingandplotting.

As listed in the coursespecificationyou will requirethe studentedition of MATLAB Version6. Thepackageincludesessentiallythesoftwareandthe installationinstructions,with detaileddocumentationprovidedonlinewithin theMATLAB environment.You shouldnow formally install theMATLAB soft-wareon your computer. The installationshouldproducean icon on the main desktopscreenof yourcomputerfrom whichyoucaninitiateaMATLAB sessionby double-clickingon theicon.

1ASCII is anacronym for AmericanStandard Codefor InformationInterchange.

(vi)

Page 9: MATLAB Short Course

Module 1

The MATLAB Workspace

1.1 Objectives

Oncompletionof thisModuleyoushouldbeableto:

• initiateaMATLAB session,accessonlinedocumentationandsetsearchpaths,

• entercommand-lineinstructionsusingbasicprogrammingoperations,

• explain theconceptsof rangeandprecisionfor thenumericaldatatypes,and

• gainfamiliarity with somebasicinbuilt MATLAB functions.

This Moduleprovidesa generaloverview of MATLAB sothatyou mayquickly gainsomeinitial handsonexperiencein usingthepackage.It is notexpectedthatyouwill necessarilybeableto graspall of thematerialpresentedin this Module,but you shouldat leastbeableto achieve theobjectiveslistedabove.Subsequentmoduleswill cover aspectspresentedherein muchmoredetail.

Reading

Palm: Chapter1 (pp.3-57)

1

Page 10: MATLAB Short Course

Module1. TheMATLAB Workspace

1.2 The MATLAB Desktop

A MATLAB sessionis startedby double-clickingon theicon on themaindesktopscreenof your com-puter. The resultingMATLAB desktopis shown as Figure 1.1-1 in Palm. The default environmentcontainsthreewindows; themainwindow ontheright handsideis thecommandwindow whereinstruc-tions maybe enteredinteractively; the top left (LaunchPad)window holdstheonline helpandsearchpathlist andthebottomleft window shows thecommandhistory. Initiate a MATLAB sessionnow sothatthis environmentappearson your computerscreen.Windows mayberesizedby holdingthemouseover the appropriatewindow borderand thendraggingleft-right or up-down. Drag the main verticalborderin themiddleof thescreento theleft soasto enlarge thecommandwindow andclick thesquareboxon thetop right of themainwindow to maximisetheMATLAB desktopon yourscreen.

Now investigatetheonlinehelpfeature.Click on the�

signbesideMATLAB in theupperleft windowto displaythe itemsbeneathit asshown in Figure1.1-1of Palm. Now double-clickon the Help iconto display the main help window. Note the links (shown in colouredtext) on the right handside tovariouscategories.Click on theMATLAB Functions Listed by Category link to displaysomeof theinbuilt functionsavailable. Click on the File I/O (file input/output)link to list someof the MATLABfunctionsassociatedwith readingandwriting files. Now click on the fopen link to seeamorecompletedescriptionof this function.This includesits syntax(how it is invoked)alongwith its argumentsor inputvariables,shown asthosewithin theroundbracketsimmediatelyafterthefunctionnamei.e. fopen(inputvariables), aswell asits returnor outputvariables,beingthosewithin thesquarebracketsprecedingtheequalssignin front of thefunctionnamei.e. [output variables]=fopen(input variables). Notethatthisparticularfunction canhave morethanoneinput andoutputvariable. In its simplestform the syntaxfor this functionis fid=fopen(filename), wherefilename is acompulsoryinputvariablewhichmustbesuppliedasan argumentto the functionandfid is an optionaloutputvariableto which is assignedthereturnvalueof thefunction.A commonform of usagefor this functionis ptr1=fopen(’fname.dat’,’rt’);which instructsthecompilerto openanexistingcomputerfile with thenamefname.dat which is in textformat(alsoknown asASCII format,asdistinctfrom binary format)for reading(not for writing) andtoassignthevariableptr1 to thereturnvalueof thefunction. This returnvariable(known commonlyasafile pointer in this case)canthenbeusedfor subsequentprogrammingstepssuchasreadingthedatainthefile, or to checkthat thefunctioncall wassuccessfullycompleted.A returnvalueof -1 for exampleindicatesthatthefile couldnotbeopenedfor readingfor somereason,themostcommonreasonfor thiserrorbeingthattheMATLAB compilercouldnot find thefile in its searchpath.More on this later.

Now try the searchfacility on the left handsideof the help screen.In the Search for: dialogueboxtypein thewordsopen file to displayall availableinformationon openingfiles within theonlinehelp.Notethefunctionfopen appearsdown thelist of thesuccessfulsearches.In thismanneracontext-basedsearchcanbe undertaken to determinewhich inbuilt functionsmight be relevant to a particulartask.A detaileddescriptionof relevant functionscanthenbe found in the right handwindow asexplainedpreviously. The Index button on the left handwindow shows an alphabeticallisting of functionsandtopics.

Now closethe help window by using the pull-down menuFile - Close Help, and double-clickonthe Path icon in the LaunchPad window. This actiondisplaysthe currentsearchpath for MATLAB

2

Page 11: MATLAB Short Course

1.3. BasicCommandsandDataTypes

functions(listedby functioncategory)asinstalledonyourcomputer. Thisessentiallytells theMATLABcompilerwhereto searchfor variousfunctionsor programs(known asM files). As you createyourown functionsandprogramslater in this subject,you will needto keeptheseseparatedfrom theinbuiltfunctionsandprogramsto make it easierfor you to find themif you wish to modify themlater. For thisreasonit is worthwhileplacinguser-definedfunctionsandprogramsin a separatedirectory(or folder)on your computer. A default folder entitledc: � matlabR12 � work (this title may be differenton yourcomputerdependingonwhereyouinstalledthesoftware)wascreatedduringinstallationfor thispurpose.

Perhapsthe most importantof the pull-down menusat the top of the main MATLAB desktopis theFile - New - M file menuwhich allows you to createyour own MATLAB functionsand/orprogramsby displayingan editor window within which you may enterMATLAB instructionsandsave thesetofile (anM file). An M file may beeithera MATLAB functionor a MATLAB program,but eachmusthave the file extension.M. A MATLAB program(a programis alsoknown asa script) typically callsa MATLAB function. For example,you might createa scriptentitledMYPROG thepurposeof whichis to reada dataseriesfrom a file andthenplot thesedata.Thescriptfile might call a functionentitledREADDATA andanotherfunctioncalledPLOTDATA, eachof which will beuser-defined;thepurposeof MYPROG beingsimply to control theoverall operationor ’flow’ of theprogram.Thenew M filesMYPROG.M, READDATA.M andPLOTDATA.M mustexist in thecurrentdirectoryor in theMATLABsearchpath.This typeof programmingis known asmodulardesign,whereamainprogramcallsseveralotherprograms(or functions)to performspecifictasks.

For thiscourseit is recommendedthatyoucreateseparatedirectoriesonyourcomputerfor eachModuleof thestudymaterialsothatyoucanreadilyfind scriptsandfunctionsyouhavecreatedfor thatparticularModule. For example,you might storeall scriptsandfunctionsassociatedwith Module1 in a directorycalledc: � ENG3103 � scripts � mod1, thoseassociatedwith Module2 in c: � ENG3103 � scripts � mod2andsoforth. A suitablerepositoryfor scriptsandfunctionsrelatingto Assignment1 of thiscoursemightbe c: � ENG3103 � scripts � assign1. Createthesedirectoriesnow so that they arereadily availableforstoringyourMATLAB programs.

Thetop right of theMATLAB desktopdisplaysthecurrentworking directoryin which your MATLABsessionis operating.Thedefault is c: � matlabR12 � work unlessyou instructMATLAB otherwise.Thecurrentworkingdirectorymaybechangedeitherby typing in thefull pathnamein thedialoguewindow,or (preferably)by clicking on thebrowsebutton(thethreedots,known asanellipsis) andselectingtherequireddirectoryfrom thedisplayeddirectorystructurefor yourcomputer. Assumingyouhave alreadycreatedadirectorycalledc: � ENG3103 � scripts � mod1, click on thisbrowsebuttonnow andselectthisdirectoryasyour currentworking directory for subsequentwork associatedwith Module 1. The fullpathnameshouldappearin thedialoguebox.

1.3 BasicCommandsand Data Types

Wenow move to themainpartof theMATLAB desktop,thecommandwindow. Notefirstly thatonlinehelp is alsoavailable from within the commandwindow. Confirm this now by typing the wordshelp

3

Page 12: MATLAB Short Course

Module1. TheMATLAB Workspace

fopen andpressingtheenterkey atthecommandprompt.Thecommandpromptis displayedas ��� withablinking cursorbesideit. This indicatesthatthecommandwindow is readyto receiveyour instructions.

Beforewe canproceedto usethecommandwindow you mustbecomefamilar with someof thebasicconceptsof programming.Studycarefullytheinformationonp.9of Palmrelatingto operatorsandorderof precedence. Theconceptof precedencein mathematicsshouldbe familar to you, however you maynotbeconversantwith thewidevarietyof operatorsavailablein MATLAB andtheirappropriatesyntax.Thesearelisted in Table1.1-1of Palm. Commenceyour interactive sessionby typing in thecommandwindow theinstructionsto implementsolutionsto themathematicalexpressionsshown in self-testT1.1-1onp.11of thetext:

clc6 � 10 � 13+18 � (5 � 7)+5 � 9ˆ 2ans =

410.12976 � 35ˆ (1 � 4)+14ˆ 0.35ans =

17.1123diary off

Thesessiondetailsabove have someadditionalstatementsworth noting. The clc commandclearsthecurrentcommandwindow andthediary on (notshown) anddiary off statementsengage/disengagealogor diary of thecurrentsession.Statementsenteredfrom thekeyboardandtheresultingoutputfrom thecommandwindow aresavedto anASCII file nameddiary (by default) in thecurrentworkingdirectory.In thiswaythesessiondetailscanberecordedfor laterinclusionin adocument,suchasthisStudyGuidefor example.Youshouldconfirmthenumericalresultabove with ahandcalculation.

Note that the output from the sessionabove is displayedto a precisionof four or five decimalplaces.This thedefault displayprecisionfor MATLAB. This canbealteredusingthe format command.Enterhelp format at the commandprompt for more information. The precisionto which calculationsareundertakenin MATLAB canbedeterminedfrom theinbuilt variableeps. Enterthisvariablenamein thecommandwindow to displayits value.Thevaluereturnedis in theorderof ��� �� �� � , whichmeansthatfloatingpoint calculationsin MATLAB aregenerallycarriedout to a precisionof aboutsixteendecimalplaces.

Example1.1-1of Palmshowsapplicationof theassignmentoperator( � ) anduser-definedvariables.Letus repeatthis exampleby creatingan M file, in the appropriatedirectoryon your own computer, withthecommandline instructionsasshown in thetext. FromtheMATLAB desktop,click themenuFile -New - M File. This will opena text editor throughwhich we canenterMATLAB commandsandsavethemto a singlefile. This file canthenbe usedlater to executethe commandssequentially. Note themenuitemsDebug andBreakpoints at thetopof theeditorwindow. Thesefacilitiesareveryusefulfordebugging code(i.e. findingwheretheerrorsarein thecodesothey canbefixed).Wewill coveraspectsof debuggingin moredetaillaterin thiscourse.

4

Page 13: MATLAB Short Course

1.3. BasicCommandsandDataTypes

Now type in the commandsasshown in the worked example,andsave the M file underthe nameofCYL.M in thecurrentdirectoryusingtheFile - Save As menuwithin theeditor. Theresultshouldlooksomethinglike:

% CYL.M% Finds the volumeof a cylinder of radius r and height h, and the radius corresponding% to a 20% increasein volume for given r and h.% Example1.1-1 of Palm for ENG3013%r=8; % Define radius of cylinderh=15; % Define height of cylinderV=pi � rˆ 2 � h; % Calculate volumeV=V+0.2 � V; % Increasevolume by 20%r=sqrt(V� (pi � h)) % Calculate and print associatedradius maintaining height 10

% EOF

Importantpointsto notefrom theabove scriptinclude:

• theuseof thepercentagesymbol(%) to allow inclusionof appropriatecommentary, suchasheaderinformationdefiningthe purposeof the script andothercommentsexplaining variousprogram-ming stepsto make thescriptmorereadable,not only to theauthorbut to otherswho might wishto modify theprogramlater,

• theuseof theinbuilt variablepi,

• theinclusionof user-definedvariablesr, h andV (notethatMATLAB is case-sensitive; thevari-ablesV andv aretwo distinctlydifferentvariablesfor example),and

• thatall linesexceptthe last (programline) areterminatedwith a semi-colon(;). This suppressesdisplayof thecurrentcontentsof thevariable,and

• theinclusionof anend-of-filemarker to show thatthescript1 is complete(finalised).

Now executethe M file by typing the nameof the file (excluding the filenameextension.M) at thecommandprompt:

cylr =

8.7636diary off

Finally, notethatthecommentaryprovidedat thebeginningof thescriptfile CYL.M canbeusedwithinthehelp facility of MATLAB. Typein thestatementhelp cyl in thecommandwindow andyou shouldseetheintroductorycommentaryat theheadof theM file:

help cyl

1Theline numberingon theright handsideof thescript/diarywasinsertedby theauthor, not by MATLAB, sothatoneormorespecificlinesof code/diaryasreproducedin this StudyGuidecanbemoreeasilyreferenced.

5

Page 14: MATLAB Short Course

Module1. TheMATLAB Workspace

CYL.MFinds the volume of a cylinder of radius r and height h, and the radius correspondingto a 20% increasein volume for given r and h.Example 1.1 � 1 of Palm for ENG3013

diary off

Theuser-definedvariablesr, h andV areby defaultof typedoubleprecision, and,althoughit maynotbeimmediatelyobvious, they arein factstoredasarrays, not assingle-valuedvariables.Workspacevari-ablesrequirecomputermemory(RAM - randomaccessmemory)to storethem,sothemoreworkspacevariablesusedin a MATLAB sessionthemoretherequiredRAM. Thewhos commandlists thedetailsof thecurrentworkspacevariables.Assumingyou have not terminatedthepreviousMATLAB session,enterthecommandwhos now:

whosName Size Bytes Class

V 1x1 8 double arrayans 0x0 0 char arrayh 1x1 8 double arrayr 1x1 8 double array

Grand total is 3 elementsusing 24 bytes10

diary off

This shows thatall theuser-definedvariables(thevariableans is not stored)in this exampleareof typedouble(doubleprecisionfloatingpointnumber),andthatthey areeachstoredasa1x1array. Eacharraythereforeconsistsof onerow andonecolumn; in otherwordsthereis only oneelementin eachof thearraysr, h andV. Beingof typedouble,eachelementof eacharrayrequires8 bytesof RAM for storage,hencethis particularsessionuses24 bytesof RAM in total to storethe threeuser-definedvariables.Otherdatatypesincludefloat (singleprecisionfloatingpoint number)requiring4 bytes,shortandlongintegers(non-floatingpoint numbers)needing2 and4 bytesrespectively, andtypechar (a singleASCIIcharacter)which requires2 bytesof RAM for storage.Refer to the output from help datatypes formoreinformation.

To illustrate the rangeable to be representedby the integer types, supposewe wish to representavery large integer (say 1234567890).Assign the user-definedvariablex to that numberby enteringx=1234567890 at thecommandprompt. By default, this numberwill bestoredby MATLAB astypedouble. Now assignanothervariableto representthis numberasa long integer (4 bytesor 32 bits) byenteringthecommandxlong=int32(x). Assignanothervariableto representit asashortinteger(2 bytesor 16 bits) by enteringxshort=int16(x), andyet anotherto representit asavery shortinteger(1 byteor8 bits)usingxvshort=int8(x). Now examinethecontentsof eachvariable:

x=1234567890

6

Page 15: MATLAB Short Course

1.3. BasicCommandsandDataTypes

x =

1234567890

xlong=int32(x)

xlong =10

1234567890

xshort=int16(x)

xshort =

32767

xvshort=int8(x)20

xvshort =

127

whosName Size Bytes Class

x 1x1 8 double arrayxlong 1x1 4 int32 arrayxshort 1x1 2 int16 array 30

xvshort 1x1 1 int8 array

Grand total is 4 elementsusing 15 bytes

diary off

It canbeseenthat theoriginal number1234567890canberepresentedby a long (32 bit) integerquiteeasily, but it obviouslycannotbestoredasashort(16bit) or veryshort(8 bit) integerbecauseit is beyondtherange thatcanberepresentedby thesedatatypes.Thelargest(positive or negative) numberthatcan

bestoredasashort(16bit) integeris��� ��������� � ! , andasaveryshort(8 bit) integer

� "������#� � ,asconfirmedby theoutputabove.

Thisaspectof rangewill notusuallypresentany majorproblemsfor you in mostsituationsprovidedyoumaintainthedefault datatypesfor numericalcalculations.Theremay be instanceshowever whereyoumight have to dealwith a largenumberof very largearraysof long integersrequiringlargeamountsofRAM for storage,to theextentthatit might tax thecapacityof your computer. Oneway of reducingtheamountof memoryrequiredis to convert the long arraysinto shortarrays,asthis will effectively halvetheRAM requirements,but beawarethatin doingso,it will notbepossibleto representany elementofthesewith a number($ ) outsidetherange�� �� !� &% $ % � � ! .

7

Page 16: MATLAB Short Course

Module1. TheMATLAB Workspace

For floating point numbersit is not so muchtherangebut theprecisionwhich is importantwhencon-vertingfrom onedatatypeto another. This is illustratedasfollows, wherein this exampleit is requiredto representthefloatingpoint number(say) ' ( ) * +�, -�. / 0�' ) * + , -�. / 0213' 4 5 6 :xdouble=1.23456789123456789e10xdouble =

1.2346e+010format longxdoublexdouble =

1.234567891234568e+010xsingle=single(xdouble)xsingle =

1.234567884800000e+010 10

whosName Size Bytes Class

xdouble 1x1 8 double arrayxsingle 1x1 4 single array

Grand total is 2 elementsusing 12 bytes

diary off

Thesingle functionconvertstypedouble(8 byteor 64 bit floatingpoint number)to typesingle(4 byteor 32 bit floatingpoint number).The format long commandswitchestheMATLAB commandwindowdisplay from the default five decimalplacesto fifteen decimalplaces. The mannerin which floatingpoint typesis storedis generallyspecificto the type of computer. The doubleprecisionfloating pointtypehasa rangeof about ' 4�798 6 : to ' 4 8 6 : anda precisionof aboutfifteensignificantfigures.Therangefor the doubleprecisionfloating point datatypeon your computercanbe determinedwith MATLABusingthecommandsrealmax andrealmin. On theauthor’s machinetherangeis from )�( ) ) ,;1�' 4 798 6 :to ' ( . 0 /21<' 4 8 6 : . The singleprecisionfloating point type hasa rangeof about ' 4 7�8 : to ' 4 8 : with aprecisionof aboutsevensignificantfigures.It canbeseenfrom theoutputabove thatthesingleprecisiondatatypeon this particularcomputerhasa precisionof abouteight significantfigures(i.e. accuratetosevendecimalplaces),hencethenumber' ( ) * +�, -�. / 0�' ) * + , -�. / 0=1>' 4�5 6 cannotbeaccuratelyrepresentedasa singleprecisionfloatingpoint type,but thereareno problemsin storingit astypedouble(to fifteendecimalplacesat least).

1.4 Arrays

As previously outlinedthedefault numericaldatatypein MATLAB is thedoubleprecisionarray. Thereareothernon-numericaldatatypesof course(themostcommonbeingof typechar (character)),but thesetoo arestoredasarrays,not assingle-valuedvariables.In thegeneralsensean arrayis a collectionofelementsof thesamedatatypestoredin rowsandcolumns;i.e. a twodimensionalcollectionof thatdata

8

Page 17: MATLAB Short Course

1.4. Arrays

type. In otherwordsan ? by @ arrayof typedoublewill consistof ? rows with @ columnsof doubleprecisionfloatingpoint numbers,andwill have a total of ?�A;@ elements.A one-dimensionalarrayhaseither ? rows andonecolumn,or onerow and @ columns,andis alsocalledavector. A singlestring (acollectionof charactersasin awordor sentence)is aone-dimensionalarrayof typechar.

As shown on p.20 of Palm, arraysconsistingof equally-spacednumericalelementscanbe initialisedusingtheconstructxarray = [xstart:xincrem:xend] wherexstart is thevalueof thefirst elementof thearray, xincrem is the (constant)incrementfor subsequentelementsandxend is the last element.Trythesearrayoperationsin theMATLAB commandwindow2:

clear;clc;xstart=1;xincrem=0.01;xend=10;xarray=[xstart:xincrem:xend];chararray=['This is a string.' ];transxarray=xarray';transchararray=chararray';xarray(1:5) 10

ans =1.0000 1.0100 1.0200 1.0300 1.0400

transxarray(1:5)ans =

1.00001.01001.02001.03001.0400

chararray(1:5) 20

ans =Thistranschararray(1:5)ans =This

whos 30

Name Size Bytes Class

ans 5x1 10 char arraychararray 1x17 34 char arraytranschararray 17x1 34 char arraytransxarray 901x1 7208 double arrayxarray 1x901 7208 double arrayxend 1x1 8 double arrayxincrem 1x1 8 double arrayxstart 1x1 8 double array 40

2Usetheclear commandto starteachexerciseto remove any previoususer-definedvariablesfrom memory.

9

Page 18: MATLAB Short Course

Module1. TheMATLAB Workspace

Grand total is 1844 elementsusing 14518 bytes

diary off

A variableis assignedto a characterarray (or string) by enclosingthe charactersin singlequotationmarks.By default a vector(one-dimensionalarray)with B elementsis storedasa 1× n array; i.e. asasinglerow with B columns.Thetransposeoperator(singlequotationmark)transposesrowsandcolumns,so that a 1× n array becomesan n× 1 array (B rows and onecolumn). Elementsof an array canbeaccessedby specifyingtherequiredindices;i.e. elementsC to D of thearrayxarray canbeprintedby thecommandxarray(1:5). In theexampleabovexarray consistsof 901elementsof typedoublein a1× 901arrayand thus requiresabout7.2 kilobytes of storage. The arraychararray consistsof 17 elements(includingblankspaces)of typecharin a1× 17 arrayanduses34bytesof memory.

The numberof elementsof an array can alsobe determinedusing the size (for two-dimensionalar-rays)or the length (for one-dimensionalarrays)inbuilt functions.Try thecommandssize(xarray) andlength(xarray) beforeyou terminatethecurrentMATLAB session.

Theuseof arraysandthe left division operatorfor thesolutionof simultaneousequationsis illustratedonp.30of Palm. Thecoefficientsareassignedto anm× n arraywhereE is thenumberof equations,B isthenumberof variablesandof courseE mustequalB otherwiseasolutionis notpossible.Theconstantsarestoredin anm× 1 columnvector. Attemptself-testT1.3-7onp.31of Palmyourself:

A=[6 F 4 8; F 5 F 3 7;14 9 F 5];B=[112;75; F 67];A G Bans =

2.0000F 5.000010.0000

whosName Size Bytes Class

10

A 3x3 72 double arrayB 3x1 24 double arrayans 3x1 24 double array

Grand total is 15 elementsusing 120 bytes

diary off

1.5 CommonMATLAB Functions and Relational Operators

A complex numberin MATLAB is representedby the symbol H or I , althoughthesevariablescanbedefinedotherwiseaswell. MATLAB will recogniseacomplex numberif it is presentedin theform x+yior x+yj whereJ and K arenumbers,i.e. withoutany multiplicationsymbolbetweeny andi (or y andj).

10

Page 19: MATLAB Short Course

1.5. CommonMATLAB FunctionsandRelationalOperators

As describedin the reading,the inbuilt functionsroots andpoly canbeusedto determinethe rootsofa polynomialfunction,or (theinverse)to determinethefunctionfrom theknown roots.Undertake self-testsT1.3-1andT1.3-2from the text to seehow thesework. Note thesyntaxfor the inbuilt functionscos andlog10. Enterhelp cos andhelp log10 at thecommandpromptfor moreinformationon theseandrelatedfunctions.Notethattheargumentof thecosinefunctionmustbein radians,notdegrees.

x1=[cos(0):0.02:log10(100)];size(x1)ans =

1 51length(x1)ans =

51x1(25)ans =

1.4800 10

coeffs=[1 6 L 11 290];mypoly=roots(coeffs)mypoly =L 10.0000

2.0000 + 5.0000i2.0000 L 5.0000i

mycoeffs=poly(mypoly)mycoeffs =

1.0000 6.0000 L 11.0000 290.0000polyval(mycoeffs,2) 20

ans =300.0000

whosName Size Bytes Class

ans 1x1 8 double arraycoeffs 1x4 32 double arraymycoeffs 1x4 32 double arraymypoly 3x1 48 double array (complex)

30

Grand total is 12 elementsusing 120 bytes

diary off

Thevectorx1 has51 elementsrangingfrom cos(0)to log(100)(i.e. from 1 to 2 inclusive) in incrementsof 0.02. Thetwenty-fifth elementis 1.48. Notethat thecoefficient matrix coeffs mustbeenteredfromleft to right in decreasingorderof theexponent. In this casethepolynomial is of order3 so therearefour coefficientsto besuppliedto thefunctionfor theexponentsM�N OPN Q and R . Thesecoefficientscanbeseparatedby commasor by blankspacesasfor any row vector. Thereis onerealroot andtwo complex(conjugate)rootsto this polynomial. Thevalueof thepolynomial S�TVU�W S�XYZQ Q S�U<O [ R at S<\]O isO T U^W`_�O X YaQ Q>_�OUaO [ R>\�M R R .Someof themorecommonrelationaloperatorsareshown in Table1.3-3of Palm. Note thedifferencebetweenthefind functionandtherelationaloperatorswheninterrogatingarrays,asshown on p.25.The

11

Page 20: MATLAB Short Course

Module1. TheMATLAB Workspace

find functionreturnsthe indicesof thearraywhoseelementssatisfycertainconditions,not thevalueoftheelementsthemselves.RepeatExample1.3-1yourselfandcompletetheself-teston p.26.

A robust list of selectedMATLAB functions,relationaloperatorsandprogrammingconstructsis pro-videdin AppendixA of Palm. More completeinformationis of courseavailablethroughtheonlinehelpfacility from theMATLAB commandwindow.

1.6 Plotting and Input/Output Operations

Theplot(x,y) commandproducesa line or point scatterplotof b againstc on a linearscale.Undertakeself-testT1.3-6onp.30of Palmby creatingasuitableM file:

% MYPLOT.M% Script for self-testT1.3-6 of Palm.%% Clear workspaceclear;clc;% Calculate polynomialsx=[0:0.001:1.5];y=4 d sqrt(6 d x+1);z=4 d x.ˆ 3+6 d x.ˆ 2 e 5 d x+3; 10

% Set plotting screen to maximumsize and plot y and z against xfigure('Position' ,get(0,'ScreenSize' ));plot(x,y,'r-' ,x,z,'g--' );xlabel('Distance (m)' );ylabel('Force (N)' );title('Force - Distance Plot' );grid;% Set x labels every 0.2mmyxticks=[0:0.2:1.5];set(gca,'XTick' ,myxticks); 20

% Set legendlabel1='y=4(6x+1)ˆ{1/2}' ;label2='z=4xˆ3+6xˆ2-5x+3' ;legend(label1,label2);% Hold plot until enter key is pressedpause;% Plot to PostScript fileorient landscape;print('-deps' ,'myplot.eps' );% Close figure window 30

close;% EOF

Somenoteworthy pointsrelatingto this scriptinclude:

12

Page 21: MATLAB Short Course

1.6. PlottingandInput/OutputOperations

• the’dot’ symbolfor scalarmultiplication/exponentiation of arrays(line 10),e.g. f&g<hji9k l ˆ mjn;ojiPk l ˆ prq`sjiPktn�m (thedotsareshown circledherefor emphasisonly); thisis analternativemethodto thepolyval functionfor evaluatingpolynomialsandwewill investigatethis in moredetail later,

• thefigure commandto settheplot areato themaximumavailablescreensize(line 12),

• useof r- and g- - to plot the first polynomial as a solid red line curve and to plot the secondpolynomialasagreendashedline3 (line 13),

• overriding the default tick spacingfor the horizontalaxis (labelsevery 0.2 m insteadof 0.5 m)(line 20),

• useof the legend commandandthemannerin whichstringsareassignedfor thelegend(lines22- 24),

• the pause commandto hold display of the plot until the returnkey is pressed(and the closecommandto closethefigurelater),and

• saving thefigurein electronicform (in this casein encapsulatedPostScriptgraphicsformat- line29) for laterprinting and/orinclusionin a documentusingtheprint command(seehelp print forlist of availablegraphicsformats).

TheresultingPostScriptgraphicis reproducedin Figure1.1.

Typical input/output(I/O) operationsin engineeringproblemsolving involve openingASCII or binaryfiles, readingdatafrom thosefiles, performingsomecomputationson the dataand outputtingsomeresults,either in tabular or graphicalformat. To openandcloseASCII or binary files for readingorwriting thecommandsfopen andfclose apply. To readandwrite binarydata,usethecommandsfreadand fwrite respectively; for ASCII datausefscanf and fprintf. Use the online help facility for moreinformationonthesecommands.Additionalinformationonfprintf formattingcodesisgivenin AppendixC of Palm(pp.586-588).Sometypical I/O operationsareillustratedin thefollowing examplewhichusesthecapacitorvoltageversustime datatakenfrom Problem5.29of Palm(p.308).

Supposethesedataarestoredin afile entitledCAPACIT.DAT andthatyouarerequiredto write aMAT-LAB scriptwhichreadsthedatafile,calculatestheaveragecapacitorvoltageandthenwritesthedataandaveragevoltageto thescreen.Theinputdataarereproducedbelow.

3Although Figure1.1 appears asthoughthesedataareplottedascurves,they arein fact plottedaslines; they appearascurvesbecausethe u valuesareveryclosetogether, producingwhatis known asa piecewiselinear fit to thepolynomialcurve.

13

Page 22: MATLAB Short Course

Module1. TheMATLAB Workspace

0 0.2 0.4 0.6 0.8 1 1.2 1.40

5

10

15

20

25

Distance (m)

For

ce (

N)

Force − Distance Plot

y=4(6x+1)1/2

z=4x3+6x2−5x+3

Figure1.1: Polynomialrelationshipbetweenforceanddisplacement

(Source: Palm (2001, self-test T1.3-6).)

Time(s)

Capacitorvoltage

(V)0.0 100

0.5 62

1.0 38

1.5 21

2.0 13

2.5 7.0

3.0 4.0

3.5 2.0

4.0 3.0

The M file might look asfollows assumingthe datain the input file arein the samecolumnarformatastheprevious table. Of courseonly thedataareenteredin thefile, with eachtime andvoltagevalue

14

Page 23: MATLAB Short Course

1.6. PlottingandInput/OutputOperations

separatedby ablankspaceandwith eachtime/voltagepairondifferentlines.

% CAPACIT.M% Readstime versus capacitor voltage from datafile CAPACIT.DAT, calculates% average voltage over total time period writes result to screen.% Data taken from Problem 5.29 of Palm.clear;clc;% Open input file for reading in ASCIIinptr=fopen('capacit.dat' ,'rt' );% Read two numbers per line of input filenumread=2; 10

% Initialise line counterlinecount=1;% Exit while loop once EOF reached for input filewhile(feof(inptr)˜=1)

% Read time and voltage as type double[tempdata,numread]=fscanf(inptr,'%f' ,2);% Make sure two values read per line before assigningto capacitor matrix% (blank lines near EOF marker in input file could produce errors otherwise)if(numread==2)

% Assign to 2xn matrix called capacitor where n is number of lines in input file 20

capacitor(linecount,1:2)=tempdata(1:2)';% Increment line counter for next iteration of while looplinecount=linecount+1;

endend% Close input filefclose(inptr);% Print data and average voltagefprintf('Time Voltage\n (s) (V)\n' );fprintf('%4.1f %6.1f\n' ,capacitor'); 30

fprintf('\nThe average voltage from time %2.1fs to time %2.1fs is %3.1fV.\n' ,. . .capacitor(1,1),capacitor(length(capacitor(:,1))),mean(capacitor(:,2)));

% EOF

with theresultingscreenoutput:

capacitTime Voltage(s) (V)0.0 100.00.5 62.01.0 38.01.5 21.02.0 13.02.5 7.03.0 4.0 10

3.5 2.04.0 3.0

The averagevoltage from time 0.0s to time 4.0s is 27.8V.diary off

15

Page 24: MATLAB Short Course

Module1. TheMATLAB Workspace

Somepointsto notein thescriptCAPACIT.M include:

• theuser-defined(file pointer)variableinptr andthesyntaxfor the fopen statement,

• thewhile loop andthe feof functionwhich actsto exit the loop oncethefile pointerreachestheendof the datafile(note that the MATLAB editor automaticallyleft-indentsthe contentsof thewhile loop to improve readabilityof thecode,andthat thewhile loop is terminatedwith theendstatement),

• thereadfunction [tempdata,numread]=fscanf(inptr,’%f’,2); which readstwo numbersat a timefrom thedatafile(eachline) astypedouble,assignsthemto a temporaryarrayvariabletempdata,andalsoreturnsthenumberof itemsreadasnumread,

• theconditionalstatementon line 19 of thescript thepurposeof which is to permitassignmentofthedataasreadto thearraycapacitor only if two numberswerereadon eachline; if otherthantwo numberswerereadtheprogramwould not enterthis block of thecode(e.g. any blank linesnearthe endof the datafilewould result in no numbersbeingreadbeforethe EOF marker4 wasfoundin thedatafile);the if statementis alsoterminatedby end,

• the line capacitor(linecount,1:2)=tempdata(1:2)’; inside the conditionalblock which assignsthe transposeof the tempdata arrayto thecurrentrow of thecapacitor array,

• theincrementfor therow (line) counteron line 23,

• theellipsisat theendof line 31signifying acontinuationto thenext line, and

• thevariablesprintedto screenon line 32 viz. capacitor(1,1) which is theelementin thefirst rowof thefirst columnof thearray(thefirst time reading),capacitor(length(capacitor(:,1))) whichdeterminesthenumberof rowsin thearrayandhenceaccessesthefirst elementin thelastrow (thelasttime reading),andmean(capacitor(:,2))); whichusestheinbuilt functionmean to calculatetheaveragevalueof all theelementsin thesecondcolumnof thearray(thevoltages).

Wewill investigatetheseconstructsandsomeof thesefunctionsin moredetail later. Readcarefullythematerialin Section1.4of Palm (pp.32-42)which furtherexplainsconditionalstatements,loopsandtheneedfor adequatecommentaryin scripts.

1.7 Problem-SolvingTechniques

Studythe materialin Palm (pp.48-56)very carefully asthis outlinesthe stepsinvolved in engineeringproblemsolvingwhich will bevery usefulto you for tutorial andassignmentwork later in this course.Beableto cite theprocedurewhich is repeatedbelow in condensedform:

4You will not beableto seetheEOFmarker in anASCII file usinga text editor; it will exist at thepoint wherethecursorstopswhenyou hold down the downarrow key on the keyboard. Note that this EOF marker is distinctly differentfrom thatmanuallyinsertedat theendof a MATLAB script(e.g.as%EOF).

16

Page 25: MATLAB Short Course

SelfAssessmentQuestions

(i) Understandtheproblemandtheassociatedengineeringprinciples.

(ii) Simplify theproblemasmuchaspossible.

(iii) Collectthenecessarydata.

(iv) Formulateanalgorithmto solve theproblem.

(v) Implementthesolution.

(vi) Performa ’reality check’on thesolution.

(vii) Qualify your answerby statingtheassumptionsusedin its derivation.

(viii) Giveyouranswerto nogreaterprecisionthanthatof theinput data.

Thisprocedurewill form thefundamentalbasisof theremainderof thework in thiscoursewhichwill fo-cusondevelopingsolutionsto bothstandardandnon-standardengineeringproblemsusingtheMATLABprogrammingenvironment.

SelfAssessmentQuestions

1.1 Theoutputfrom theMATLAB instruction5+3/6 will be:

(a) 7.00

(b) 5.50

(c) 1.33

(d) 5.00

(e) noneof theseanswers

1.2 Usingthedefault namingconventionin MATLAB, anm× 1 arrayhas:

(a) v rows and w columns

(b) v columnsand1 row

(c) v rows and1 column

(d) 1 row and1 column

(e) noneof theseanswers

1.3 Thenumericalrangeof a16 bit integeris approximately:

(a) x>y z(b) xt{(c) x>y | }(d) x~ | } z }(e) noneof theseanswers

17

Page 26: MATLAB Short Course

Module1. TheMATLAB Workspace

1.4 A vectorarraycontains10000elementsof typedouble.Thestoragerequirementsfor thisarrayisapproximately:

(a) 10megabytes

(b) 32kilobytes

(c) 80kilobytes

(d) 10kilobytes

(e) noneof theseanswers

1.5 Theassignmentx=[1.1, 1.2, 1.3, 1.4; 2.1, 2.2, 2.3, 2.4] will besuchthat thevariablex will beanarraywith:

(a) 4 rows and4 columns

(b) 4 rows and2 columns

(c) 2 rows and4 columns

(d) 1 row and8 columns

(e) noneof theseanswers

1.6 If x=[1.5, 3.9, 5.8, 7.3], theoutputfrom theMATLAB instructionfind(x � 5) will be:

(a) [1, 2]

(b) [1.5, 3.9]

(c) [1.5, 3.9, 5.8]

(d) [3, 4]

(e) noneof theseanswers

1.7 If x=[0:1:10], theoutputfrom theMATLAB instructionlength(x) will be:

(a) 10

(b) [1, 11]

(c) 11

(d) [1, 10]

(e) noneof theseanswers

1.8 If x=2+3i andy=3-6i, theoutputfrom theMATLAB instructionx+y will be:

(a) -1+9i

(b) 5-3i

(c) 24-3i

(d) 5

(e) noneof theseanswers

18

Page 27: MATLAB Short Course

TutorialProblems

1.9 If x=2+3i andy=3-6i, theoutputfrom theMATLAB instructionx*y will be:

(a) -1+9i

(b) 5-3i

(c) 24-3i

(d) 5

(e) noneof theseanswers

1.10 The problem-solvingexampleusing the falling packagein the text by Palm (p.51) shows thatthe terminal velocity of the package� is relatedto the fall height � by �#��� � ��� . Given alocal gravitationalacceleration� of 9.807m/s� , the terminalvelocity of a packagefalling from ameasuredheightof 0.575m is about3.3582808m/s. Consideringtheprecisionof the input datafor themathematicalmodelof thisproblem,thecalculatedvelocityshouldbeexpressedas:

(a) 3.3582808m/s

(b) 3.0m/s

(c) 3.358m/s

(d) 3.36m/s

(e) noneof theseanswers

Tutorial Problems

Note: Model solutionsareprovidedin AppendixA for thetutorial problemsindicatedthus( � ). Be surethatyou

makeanhonestattemptat theproblembeforeconsultingthemodelsolutions.

1.1 PalmProblem1.2

1.2 PalmProblem1.7

1.3 PalmProblem1.10�1.4 PalmProblem1.12 [21 elements,�P� � �j�^�r��� ��� � � ]1.5 PalmProblem1.14�1.6 PalmProblem1.18�1.7 PalmProblem1.23�1.8 PalmProblem1.24 [ �&�a�=� � ���a� � � �t�3� ]1.9 PalmProblem1.26 [ � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � ]

1.10 Fill avectorarrayof typedoublerangingfrom �>��3�  �¡ � to ���2�   � with its elementsincreasingin incrementsof 0.005. Print elements1207 to 1210 inclusive using fprintf with the followingformats:

19

Page 28: MATLAB Short Course

Module1. TheMATLAB Workspace

• ononeline in scientificnotationwith afield width of 15andwith 3 decimalplaces,and

• onseparatelinesin decimalnotationwith afield width of 8 andwith nodecimalplaces.

How muchcomputermemorywouldberequiredto storetensucharrays?

(Hint: ReferPalmAppendixC for fprintf formattingcodes.)

[6.040e+000etc.;6 etc,;approx.1.6Mb]

SelfAssessmentQuestions

Solutions

Table1.1: Solutionsto self assessmentquestions- Module1

Solution Comment

1.1 (a) divisionhasprecedenceoveraddition

1.2 (c) conventionis row first thencolumn

1.3 (d)

1.4 (c) ¢ £ £ £ £ elements@ 8 bytes= 80000bytes ¤ 80kb

1.5 (c) eachline (terminatedwith asemicolon)of datarepresentscolumnsof onerow

1.6 (a) find returnsindices,notvalues

1.7 (c) therewill be11 elements;(b) is thereturnfrom size(x)

1.8 (b) ¥�¦;§>¨a© ª=¦�« ¬9¦�© «V­�® ¬ ¯�¨�°V­�« ¯1.9 (c) ¥�±²§�¨a© ª=¦2« ¯ ¬9±=© «V­�® ¯ ¬j¨3®=¦2³ ¯9­3¢ ª ¯9­2¢ ´ ¯ µr¨�ª ¶t­;« ¯1.10 (d) theinputdatahaveno greaterprecisionthanthreesignificantfigures

20

Page 29: MATLAB Short Course

Module 2

Array and Matrix Operations

2.1 Objectives

Oncompletionof thisModuleyoushouldbeableto:

• createmultidimensionalarraysin MATLAB,

• undertake basicarray, vectorandmatrix operations,and

• performalgebraicoperationsonpolynomials.

2.2 CreatingArrays

Reading

Palm: Section2.1(pp.65-76)

21

Page 30: MATLAB Short Course

Module2. Array andMatrix Operations

As indicatedin thepreviousModule,anarrayis simplyacollectionof elementsin rows(· ) andcolumns( ¸ ). This collectionof elementsmayserve a specificpurposeor specialalgebraicmeaning(ratherthansimplygroupingelementstogether),in whichcasethenomenclaturematrixandvectoris generallyused.A vectorcanbeeithera m× 1 arrayor a 1× n array, whereasa matrix is anm× n (i.e. two-dimensional)array. Arraysarecreatedin MATLAB by enteringdatarow-wisefirst, asindicatedin thetext; i.e. arrayelementsfor eachrow (separatedby a blankspaceor a comma)areenteredfirst, therow is terminatedwith a semicolonandtheelementsfor thenext row areenterednext, andsoforth; sothat,for example,in orderto storearray1 definedby:

array1 ¹ º»»¼ ½ ¾ ¿ÁÀP¾ ÀÃÂ�¾ ÄÅÆ ¾ ÄÁÀP¾ ÂÃÇ�¾ ÄÈ9¾ ¿ ÅÆ ¾ ÀÃÀ�¾ ÈÉ ÊÊË

oneenterstheMATLAB command:

array1 = [1.5, 2.2, 9.8; -7.8, 2.9, 0.8; 4.5, -7.2, 2.4];

wherethe trailing semicolonoutsidethesquarebracketssuppressessubsequentdisplayof the variablearray1 to thescreen.Alternatively, the3× 3 arraycanbecreatedby joining together(concatenating)aseriesof threem× 1 arraysdefinedby:

vector1 ¹ÍÌ ½ ¾ ¿ÃÀ�¾ ÀÎÂP¾ Ä�Ïvector2 ¹ÍÌ Å�Æ ¾ ÄÎÀP¾ ÂÃÇ�¾ Ä�Ïvector3 ¹ Ì È9¾ ¿ ÅÆ ¾ ÀÃÀ�¾ È Ï

usingtheMATLAB command:

array1 = [vector1; vector2; vector3];

or thecommand:

array1 = cat(1,cat(1,vector1,vector2), vector3);

Sequentialelementsof anarrayareaddressedusingthecolonsymbol(:). For example,to determinetheelementsof thesecondrow of array1 whicharegreaterthanzero,oneenters:

array1(2,find(array1(2,1:3) Ð 0))

whichaddressestheelementsin columns1 to 3 of thesecondrow of thearray. Sincethisarrayhasonlythreecolumnsin any case,thesameoperationcanbeundertakenusing:

array1(2,find(array1(2,:) Ð 0))

wheretheomissionof theindicesoneachsideof thecolonmeansall columnsof thesecondrow.

Self-Test 2.1

Palm:T2.1-1 Ñ (p.76)T2.1-2 Ñ (p.76)

Modelanswersareprovidedin AppendixA for theself-testsindicatedthus( Ò ). Besureto makeanhonestattempt

at theproblembeforeconsultingthemodelsolutions.

22

Page 31: MATLAB Short Course

2.3. VectorandMatrix Operations

2.3 Vector and Matrix Operations

Reading

Palm: Sections2.2- 2.4(pp.76-100)

Beforeproceedingwith MATLAB implementationsof theseoperationsit maybeworthwhileatthisstageto revisesomeof thebasicpropertiesandmathematicaloperationsassociatedwith vectorsandmatrices.Youshouldhave coveredthesebasicconceptsin earliersubjects.

BasicPropertiesof Vectorsand Matrices

• The zero matrix containsall zeros. An m× n array can be initialised in MATLAB using ze-ros(m,n).

• A matrix is saidto besquare if thenumberof rows equalsthenumberof columns(i.e. Ó = Ô ).• A squarematrix is termeddiagonal if all theelementsnot on themaindiagonal(viewedfrom top

left to bottomright) arezero.

• Theidentitymatrix is adiagonalmatrixwith all elementsonthemaindiagonalequalto unity. Theidentity matrix1 I is suchthatA * I = A. Them× m identity matrix is createdin MATLAB usingeye(m). A diagonalmatrix canbecreatedwith MATLAB usingdiag(n), whereÔ is thevectorofelementsrequiredfor themaindiagonal.

• An uppertriangular matrix is squarewith every elementbelow themaindiagonalequalto zero.The uppertriangularpart of a squarematrix A canbe extractedwith the MATLAB commandtriu(a).

• The transposeof a matrix ( Õ;Ö ) is suchthat ÕØ×�Ù Õ�ÖrÚtÖ andis obtainedby reversingtherowsandcolumns;i.e. the elementsin eachrow of the matrix are the sameasthe elementsin eachcolumnof its transpose.TheMATLAB commandAÛ (singlequotationmark)transposesmatrixA.

• The inverse( Õ�Ü²Ý ) of a squarematrix A is onesuchthat ÕßÞ=Õ2Ü�Ý�×�à . Not all matriceshave aninverse. A squarematrix is callednonsingularwhenit doeshave an inverseandsingular whenit doesnot. An m× m matrix is nonsingularwhenits rank equalsÓ . TheMATLAB commandsrank(A) andinv(A) determinetherankandinverserespectively of matrix A. Theinversecanalsobe found by left division of the matrix by the identity matrix Õ2Ü�Ý3×ØÕ�á à , accomplishedwithMATLAB usingA á eye(size(A)).

1By conventiona matrix is usuallysymbolisedmathematicallyasanuppercaseboldfaceletteranda vectorasa lowercaseboldfaceletter.

23

Page 32: MATLAB Short Course

Module2. Array andMatrix Operations

• The determinantof a squarematrix hasa similar purposeto the discriminant â ã äVå3æ�ç�è é which

appearsin thesolutionof thequadraticequationç ê ä²ë ã ê ë ètì�í givenby ê�ì åãrî<ï ã ä å3æ�ç�èð ç(with whichyoushouldbefamiliar),andis very usefulfor thesolutionof simultaneousequationswhichyouwill studylaterin this subject.Thedeterminantof a2× 2 matrix is givenby:

if ñòìôóõ çPö ö÷çPö äç ä ö÷ç ä äøù

then detú ñ�ûüìýçPö ö ç ä ä å^çPö ä ç ä öwherethesubscriptç þ ÿ refersto theelementin the � � � row andthe � � � columnof thearrayA. Thedeterminantof a3× 3 matrix is:

if ñòì ó��õ çPö öüçPö ä çPö �ç ä öüç ä ä ç ä �ç�� öüç�� ä ç�� �ø ��ù

then detú ñ�ûüì çPö ö ç ä ä ç�� �Vå�çPö ö ç ä � ç�� ä å�çPö ä ç ä ö ç�� � ë çPö ä ç ä � ç�� ö ë çPö � ç ä ö ç�� ä å�çPö � ç ä ä ç�� öThedeterminantof anuppertriangularmatrix is theproductof theelementson thediagonal.Asingularmatrix hasa determinantof zero. The determinantof the squarematrix A is found inMATLAB usingdet(A).The useof the inversefor the solutionof simultaneousequationscanbe difficult when the co-efficient matrix A in the simultaneousequationsñ� ì� is nearly singular. The solution is�^ì�� ñ�ì�jñ�� ö for which theprior calculationof theinverseñ � ö is required.Thepreferredsolutiontechniquein MATLAB is to usetheleft division operatorsothat �^ìZñ�� in which thecoefficient matrix is not inverted,andthe solutionis achieved by a processknown asGaussianelimination. Seehelp inv for moredetail.

Mathematical OperationsAssociatedwith Vectorsand Matrices

Considerthefollowing arrays.A andB are2× 4 arraysandC is a3× 2 array:

ñ ì óõ çPö öüçPö ä çPö �÷çPö �ç ä öüç ä ä ç ä �÷ç ä �øù�� ì óõ ã ö ö÷ã ö ä ã ö � ã ö �ã ä ö÷ã ä ä ã ä � ã ä �

øù � ì ó��õ è ö öüè ö äè ä öüè ä äè � öüè � äø ��ù

For array or matrix addition the arraysmustbe the samesizeandthe sumof A andB is determinedelement-by-elementas:

ñ ë � ì óõ çPö ö ë ã ö ö÷çPö ä ë ã ö ä çPö � ë ã ö �÷çPö � ë ã ö �ç ä ö ë ã ä ö÷ç ä ä ë ã ä ä ç ä � ë ã ä �÷ç ä � ë ã ä �øù

This summationis carriedout in MATLAB using the command:A + B. This also appliesfor arraysubtraction.

24

Page 33: MATLAB Short Course

2.3. VectorandMatrix Operations

For array multiplication the arraysmustbe the samesizeand the arrayproductof A andB is foundelement-by-elementusing: ���������! " #�! $ " $%�! & " &%�! ' " '��$ " $ #��$ $ " $ $%��$ & " $ &%��$ ' " $ ' ()which is achievedin MATLAB usingA.*B. Thesameappliesfor arraydivisionandexponentiation,andfor themultiplication,divisionandexponentiationof anarrayby aconstant.

For matrixmultiplicationthearraysmustbesuchthatthenumberof rows in themultiplier is thesameasthenumberof columnsin themultiplicand.For examplethematrix productA * B is undefinedbecausethemultiplier (B) has2 rows andthemultiplicand(A) has4 columns.Similarly thematrix productA *C is undefinedsincethemultiplier (C) has3 rows andthemultiplicand(A) has4 columns.However thematrixproductC * A doesexist andis definedby:

*�+,�-� �..�0/ �! �1 / $ ��$ / �! $21 / $ ��$ $ / �! &21 / $ ��$ & / �! ',1 / $ ��$ '/ $ �! �1 / $ $ ��$ / $ �! $21 / $ $ ��$ $ / $ �! &21 / $ $ ��$ & / $ �! ',1 / $ $ ��$ '/ & �! �1 / & $ ��$ / & �! $21 / & $ ��$ $ / & �! &21 / & $ ��$ & / & �! ',1 / & $ ��$ '( 33)

andthusthematrixproductof anm × n array(themultiplicand)andanm$ × n$ array(themultiplier) isdefinedwhen 4�$ �65 andtheresultis anm × n$ array. TheassociatedMATLAB commandis C * A.

Now considerthefollowing 1× 3 arrays:78�:9<; ; $ ; &>= ? �:9<@ @ $ @ &�=Thedotproductof two 1× n arraysis a1× 1 array(i.e. ascalar)givenby:7�A ? � ; @ �1 ; $ @ $21 ; & @ &In MATLAB thedotproductd

Aecanbeobtainedin anumberof ways:

• usingthecommanddot(d,e) or,

• if bothd andeare1× n arrays(asabove),by usingd*eB , or,

• if d andearebothn× 1 arrays,by usingd B *e,

whereeB is thetransposeof e (andd B is thetransposeof d).

Thecrossproductof two 1× n arraysis a1× n arraygivenby:7DC ? �:9E; $ @ &EF ; & @ $ ; & @ 2F ; @ & ; @ $,F ; $ @ >=Thecrossproductd

Cecanbedeterminedwith MATLAB usingcross(d,e).

25

Page 34: MATLAB Short Course

Module2. Array andMatrix Operations

Thedot andcrossvectorproductsareusedextensively in engineering.Thedot product G6H I givesthecomponentof theforceF in then direction.ThecrossproductJLK>G givesthemomentof forceF aboutany point wherer is thepositionvectorfrom thatpoint to any point on theline of actionof F.

Self-Test 2.2

Palm:T2.3-1 M (p.90)T2.4-1 M (p.93)T2.4-2 M (p.93)

2.4 Polynomials

Reading

Palm: Section2.5(pp.100-105)

TheMATLAB functionsapplicableto polynomialalgebraaredescribedin this section.Take particularnoteof the conv anddeconv functionsfor polynomialmultiplication anddivision respectively. Thefunctionspoly, polyval androots wereintroducedin thepreviousModule.

Example2.5-1of Palmshowshow thesemaybeappliedtosolveatypicalstructuralengineeringproblem.Thecharacteristicpolynominaldescribingthenaturalfrequencies( N ) of a multistorybuilding aregivenin theexampleas: O PRQ NTS U�V O W P�Q NXS U S QDP S Y<Z P S NXS Q W P\[^]`_aXb O a SS QcP S ULZ a [ ]`_ (2.1)

whereP is aconstantand:aXb%]dP�Q NXSfe a S ]W PRQ NTSge a [ ]hP S NXS Q W P\[

The degreeof this polynominalin N is 2, hencethreeelementsare requiredto describethe arrayofcoefficientsfor eacha . For aXb the coefficient arrayis i Qkj lm_�lmPTn correspondingto the coefficientsof N S , N b and NXo respectively. For a S thecoefficientsare i Qkj l^_!l W PTn andfor a [ thecoefficientsarep P S lm_�l W P [ q . Theline of thescriptshown asp4 = conv(p2,p2)-[0, 0, 0, 0, P S ) firstly squaresa Sin accordancewith thefirst termin thebracketsin Eqn.(2.1)by convolving it with itself; this produces

26

Page 35: MATLAB Short Course

2.4. Polynomials

a coefficient array of five elements(i.e. r sTt u t will have four coefficients and thereis one more forthe constantsXv giving a total of five) so in order to subtractw\t from xytt the coefficient array for w\tmustbeexpressedas z {!|m{�|m{!|^{!|mw t } correspondingto thecoefficientsof sy~ , sX� , s t , s\� and s vrespectively. At this stagein thescript,Eqn.(2.1)hasbeenreducedto:x � x ~,� x �^� { (2.2)

Theline shown asp5 = conv(p1,p4) multipliespolynomialx � by x ~ to createthefirst termin Eqn.(2.2)thusreducingthecharacteristicequationto: xy� � x ��� { (2.3)

Thenext line p6 = p5 + [0, 0, 0, 0, p3] completestherelationshipin Eqn.(2.3).r = roots(p6) solvesfor therootsof Eqn.(2.3)andtheline pos=r(r � 0) extractsthepositive roots.

Thesizeof eachvectorof coefficientsis summarisedasfollows:

Variable Numberof elements�!� ���� ���� �� � (numberin ��� ) �\�2�R�2�c�<�0�,�R�2�c���� (numberin ��� ) � (numberin �!� ) �E�2�c��� � ���,�D���� sameas���� � � � � � � � � ��� � ( � (zeros))� (numberin ��� ) �R�,� � �D�(mustbesamenumberas��� to addto ��� )

Self-Test 2.3

Palm:T2.5-1 � (p.104)T2.5-2 � (p.104)T2.5-3 � (p.104)

27

Page 36: MATLAB Short Course

Module2. Array andMatrix Operations

SelfAssessmentQuestions

2.1 If ���m��� ¢¡�£<¤g¥£,¦¨§m©©ª¥�©« ¬¬­ thenthe output from the MATLAB instructionA(2,find(A(2,:)) ® 0))

will be:

(a) 7

(b) -4

(c) 12

(d) 5

(e) noneof theseanswers

2.2 If ���m��� ¢¡�£<¤g¥£,¦¨§m©©ª¥�©« ¬¬­ thenthe output from the MATLAB instructionA(find(A(2,:)) ® 0),1)

will be:

(a) 7

(b) -4

(c) 12

(d) 5

(e) noneof theseanswers

2.3 If �¯�°��� ¢¡�£<¤g¥£,¦¨§m©©ª¥�©« ¬¬­ thentheoutputfrom theMATLAB instructionsum(A(:,2)) will be:

(a) 7

(b) -4

(c) 12

(d) 5

(e) noneof theseanswers

28

Page 37: MATLAB Short Course

SelfAssessmentQuestions

2.4 If ±¯²°³´´µ¢¶�·<¸g¹·,º¨»m¼¼ª¹�¼½ ¾¾¿ thenmatrixA is saidto be:

(a) diagonal

(b) square

(c) uppertriangular

(d) lower triangular

(e) noneof theseanswers

2.5 Selectthecorrectstatement:

(a) theidentitymatrix is uppertriangular

(b) all matriceshave aninverse

(c) theMATLAB commandA À determinestheinverseof matrix A

(d) asingularmatrixhasanon-zerodeterminant

(e) noneof theseanswers

2.6 Thesumof two matricesis definedonly wheneachmatrix is:

(a) thesamesize

(b) diagonal

(c) square

(d) non-singular

(e) noneof theseanswers

2.7 If ±Á² ³´´µ¢¶�·<¸g¹·,º¨»m¼¼ª¹�¼½ ¾¾¿ and ÂòÅÄ ·<ÆmÇmÈ

Éthenthematrix productA * B canbeobtained

usingtheMATLAB command:

(a) A*B

(b) A.*B

(c) A Ê B(d) A/B

(e) noneof theseanswers

29

Page 38: MATLAB Short Course

Module2. Array andMatrix Operations

2.8 If ËÁÌ°ÍÎÎÏ¢Ð�Ñ<ÒgÓÑ,Ô¨ÕmÖÖªÓ�Ö× ØØÙ and ÚÃÌÅÛ Ñ<ÜmÝmÞ

ßthenthematrix productB * A canbeobtained

usingtheMATLAB command:

(a) B*A

(b) B.*A

(c) B à A(d) B/A

(e) noneof theseanswers

2.9 If ËÅÌ ÍÎÎÏáÐgÑEÒgÓÑEÔâÕmÖÖªÓ�Ö× ØØÙ and ÚÁÌãÛ ÑEÜmÝmÞ

ßthenthearray productB * A canbeobtained

usingtheMATLAB command:

(a) B*A

(b) B.*A

(c) B à A(d) B/A

(e) noneof theseanswers

2.10 Thearrayof coefficientsof thepolynomial Ò ä å2æ Þ ä ç ÑDÐ ä æ Õ wouldbeexpressedin MATLABas:

(a) [2, 3, -7, 5]

(b) [5, 3, 1, 0]

(c) [5, -7, 3, 2]

(d) [2, 0, 3, 0, -7, 5]

(e) noneof theseanswers

Tutorial Problems

Dueto the increasingcomplexity of someof theseproblems,it would beadvantageousat this stagetobegin encodingyoursolutionsinto M files.

2.1 PalmProblem2.3è2.2 PalmProblem2.5è

30

Page 39: MATLAB Short Course

TutorialProblems

2.3 PalmProblem2.13

2.4 PalmProblem2.14é2.5 PalmProblem2.15é2.6 PalmProblem2.18é [ êìëDí î ï ð í ft, ñ�ëcò î ï ó ô ft, $5157]

2.7 PalmProblem2.22é [maximum õyö when ê2÷0ëcê2ö ]2.8 PalmProblem2.25é [maximumL/D when ø>ë 3.8°]

2.9 PalmProblem2.30é[at ùTëcú s,positionvectoris [2, 53,0], angularmomentumvectoris [0, 0, 100]with magnitudeof 100Nms

in the û direction]

2.10 A forceof 600N actsthroughthepoint ü�ýhþ , ÿý�� , �Lý�� atanangleof 40° below thepositiveü direction.Usingthecrossproductfunctionin MATLAB, determinethemagnitudeanddirectionof themomentof theforceabouttheorigin. [2.61kNm in negative û direction]

2.11 A forceof 100N is appliedat theorigin andpassesthroughthepoint ü�ý�� , ÿý�� , �0ý�� . Usingthedot productfunctionin MATLAB, determinethecomponentof theforcealongtheline whichpassesthroughtheorigin andthepoint ü�ý�� , ÿý�� , �Lýhþ . [84.4N]

2.12 PalmProblem2.31é2.13 PalmProblem2.32é [ ú ��� �î ú ��� �í í � �����ò ô ò ��� �� î ��� Rí � ò ���� ð ]2.14 PalmProblem2.33

2.15 PalmProblem2.34

31

Page 40: MATLAB Short Course

Module2. Array andMatrix Operations

SelfAssessmentQuestions

Solutions

Table2.1: Solutionsto self assessmentquestions- Module2

Solution Comment

2.1 (d) A(2,2) = 5

2.2 (b) A(2,1) = -4

2.3 (e) ����� ���"!$# %2.4 (b)

2.5 (e) nonecorrect

2.6 (a) undefinedif differentsizes

2.7 (e) is undefined;errormessagewill resultif A*B usedsincemultiplier hasonerow andmulti-plicandhasthreecolumns

2.8 (a) is defined;multiplier hasthreerowsandmultiplicandhasthreecolumns

2.9 (e) is undefined;errormessagewill resultif B.*A usedsincemultiplier andmultiplicandareofdifferentsize

2.10 (d) six elementsrequiredfor fifth orderpolynomial

32

Page 41: MATLAB Short Course

Module 3

Files,Functionsand Data Structur es

3.1 Objectives

Oncompletionof thisModuleyoushouldbeableto:

• importexternaldatainto MATLAB,

• createMATLAB scriptsandfunctionfiles,

• storeandretrieve MATLAB workspacevariables,

• useelementarymathematicalfunctions,and

• createandapplythecell andstructure datatypes.

3.2 Data Import and Export

Reading

Palm: Sections3.1- 3.2(pp.117-126)

33

Page 42: MATLAB Short Course

Module3. Files,FunctionsandDataStructures

Datacontainedin anASCII file canbe importedinto MATLAB with the load datafile command.Thedatafilemustcontainthe dataonly with no headerinformationor otherdescriptives. Eachline of thedatafileholdselementsof thecolumnsof thearrayto beimported,eachseparatedby a space,with onerow per line. The workspacevariableimportedthis way takeson the nameof the datafile(minustheextension).Superfluousheaderinformationandcommentarywithin thedatafilecanbe removed usingany text editor (suchasDOS EDIT or Windows notepad), or within the MATLAB commandwindowusingtheMATLAB commandedit datafile.

Datacontainedin a spreadsheetprogramarein binary format. To load thesedatainto MATLAB theycanbesaved in space-delimitedASCII format from within thespreadsheetprogramandthenimportedasabove, or they canbe importeddirectly from the spreadsheetbinary file usingthe wk1read (Lotus1-2-3format)or xlsread (MSExcelformat)commands.

The save datafile commandexportsdatafrom a MATLAB sessionasshown on p.125of Palm. The-ASCII flag savesthemin space-delimitedASCII format,otherwisetheexport is in binaryformat. Thedlmwrite commandallows theuserto specifyadelimiting characterotherthanaspace.

MATLAB workspacevariablescanbesavedto file for laterretrieval with thecommandsave filenamevariables.

3.3 BasicI/O and Mathematical Functions

Reading

Palm: Sections3.3- 3.4(pp.126-137)

Example3.3-1shows anapplicationof thedisp command.Note that thesameoutputcanbeobtainedusingfprintf with a little manipulation:

table2(1,:)=ntable2 =

2 3 4 5 6 7 8 9 10table2(2,:)=C. & 1e12table2 =

Columns 1 through 72.0000 3.0000 4.0000 5.0000 6.0000 7.0000 8.00004.4250 8.8500 13.2750 17.7000 22.1250 26.5500 30.9750

Columns 8 through 99.0000 10.0000 10

35.4000 39.8250fprintf('\n %10.0f %20.3f' ,table2);

34

Page 43: MATLAB Short Course

3.3. BasicI/O andMathematicalFunctions

2 4.4253 8.8504 13.2755 17.7006 22.1257 26.5508 30.975 20

9 35.40010 39.825

diary off

Whena matrix is the argumentto fprintf, the commandwill cycle throughthe elementsof the matrixcolumnby column, so in order to print numberof plateswith associatedcapacitance,the n vector isinsertedinto the first row of the matrix table2 and the C vector into the secondrow. The first itemprinted with fprintf will be the first elementin the first column of the table2 matrix ('�( in %10.0fformat), theseconditem printedwill be thesecondelementin thefirst column( )*( in %20.3fformat),thethird itemwill bethefirst elementin thesecondcolumn(',+ in %10.0fformat),thefourthwill bethesecondelementin thesecondcolumn( )�+ in %20.3fformat)andsoon.

Theinput andmenu commandsareusefultoolsfor promptingakeyboardor mouseinput from theuser.

Self-Test 3.1

Palm:T3.3-1 - (p.130)T3.3-2 - (p.130)T3.3-3 - (p.130)

Notecarefullythelist of commonmathematicalfunctionsgivenin Tables3.4-1,3.4-2and3.4-3of Palmbeforeattemptingtheself-testswhich follow.

Self-Test 3.2

Palm:

T3.4-1 - (p.134)T3.4-2 - (p.134)T3.4-3 - (p.136)T3.4-4 - (p.136)T3.4-5 - (p.136)T3.4-6 - (p.136)

35

Page 44: MATLAB Short Course

Module3. Files,FunctionsandDataStructures

3.4 User-DefinedFunctions

Reading

Palm: Section3.5(pp.137-149)

Up to this point we have usedM files asstandaloneprogramswith all of thecomputationalinstructionscontainedwithin a singlefile. A morepreferredform of programdesigninvolvestheuseof functions,wherebyoneor morefunctionfiles arecalledby themainprogramto performspecifictasksfollowingwhich control is returnedbackto themaincalling program.This typeof programming(calledmodularprogramming)makes the main programmore compactand thus enablesthe programmer(and otherswhomighthave to modify it later)to moreeasilydesignand/orfollow the’flow’ of theprogramwithouthaving to firstly designand/ordecipherthecomputationaldetails.Modulardesignis alsomoreefficientas it increasesversatility by enablingthe samefunction to be calledby many differentprograms(theinbuilt fprintf functionis a goodexample).

Functionsin MATLAB mayhavemultipleinputandoutputvariables.Functionsarecalledfrom themainprogramby issuingthenameof the functionon theMATLAB commandline or in a MATLAB script.TheM file containingthefunctioncodemusthave thesamenameasthefunctionandthefirst word onthefirst line of thefunctionfile mustbe function. Notethatvariablesdefinedwithin functionsarelocalto thatfunction. Variablesdefinedwithin themainscriptor within any of thefunctionscalledby it maybemadeavailableto all modulesof theprogramusingthecommandglobal variable names.

Example3.5-1(p.140)of Palm illustratesthesyntaxfor functionsandtheuseof local andglobalvari-ables.Notethatthefunctionsusedin thisexampleconsistof only oneor two linesof codehencethereisnot a lot to begainedin termsof compactnessor improvedreadabilityof codeby placingtheseinstruc-tions in a separatefunctionfile. However functionsmay typically comprisemany hundredsof linesofcodeand,if multiple calls to thesamefunctionarerequiredto implementthesolutionto theproblem,thentheadvantagesof modularprogrammingbecomemuchmoreapparent.

Thelatterpartof thissectionof thereadingshowshow to usethepredefinedfunctionsfzero andfminbndfor finding the rootsandminimumvaluesrespectively of a user-defined(algebraic)function. Thecon-tentsof the functionfile fzero.m canbeexaminedby typing edit fzero.m on theMATLAB commandline. Notethatthisparticularfunctionhasalmost500linesof code.

The fzero functionreturnsthevalueof . in thefunctionalrelationship1 /�0 fn 1 .,2 wherethevalueof /changessign,i.e. wheretheplot of / against. crossesthe . 0�3 axis. fzero will notbeableto determinethevalueof . correspondingto fn 1 .,2 043 if theplot of / against. touchesthe . 043 axis. In any casethefunctionalrelationship/�0 fn 1 .,2 shouldalwaysbeplottedto confirmtheoutputof suchfunctions.

1 5$6 fn 7 8 9 is theauthor’s shorthandfor ’ 5 is a functionof 8 ’.36

Page 45: MATLAB Short Course

3.4. User-DefinedFunctions

Thefminbnd functiondeterminestheminimumvalueof : in thefunctionalrelationship;=< fn > :,? overauser-definedinterval. Thiswill notnecessarilybethevalueof : wheretheslopeof theplot of ; against: changessign,but simply thevalueof : where ; is at its minimumvalueover someinterval. This isillustratedin Fig. 3.5-2of Palm. Thevalueof : suchthatfn > :,?�<�@�A @ B C :ED$FG@�A @ H B C :JI*FK@�A L L L :EM�NK:EOis at its minimum valueover the interval @�A P QR:�QSB�A C is 0.1001. The slopeof the plot of ; against: changessignat : valuesof about0, 2 and2.8. The ; valuesat :G<R@ and :G<RB�A T arelocal minimawhereasthe ; valueat :�<UB is a local maximum. This canbe confirmedusingthe MATLAB rootscommandandsomeelementarycalculus.Now a minimum or a maximumvalueof ; will occurwhenV ;V : <�@ . It will beaminimumwhen

V O ;V : O is positive andit will beamaximumwhenV O ;V : O is negative.

now ;W<X@�A @ B C : D FK@�A @ H B C : I FG@�A L L L : M NG: Oso

V ;V : <X@�A P B C : I FK@�A B C : M FK@�A Y Y Y : O NGB :and

V O ;V : O <X@�A C : M FK@�A Z C : O F[P A Y Y T :=NGBUsingtheMATLAB command:

roots([0.125, -0.25, -0.999, 2, 0])

yieldstheresult:

V ;V : <X@�A P B C : I FK@�A B C : M FK@�A Y Y Y : O N[B : <�@ when : <\]]]]]^

@F�B�A T B TB�A T B TB�A @

_ `````a

whereby:

V O ;V : O <X@�A C : M FK@�A Z C : O F[P A Y Y T :=N[B for : <\]]]]]^

@F�B�A T B TB�A T B TB�A @

_ `````a

canbeevaluatedwith thepolyval commandyielding:

polyval([0.5, -0.75, -1.998, 2],[0, -2.828, 2.828, 2.0]) = [2.000, -9.656, 1.660, -0.996]

which provesthat ; haslocal minima at :�<b@ and :�<bB�A T B T sincecorrespondingvaluesofV O ;V : O of

2.000and1.660aregreaterthanzero,andlocalmaximaat : <4F*B�A T B T and: <�B�A @ sincecorresponding

valuesofV O ;V : O of -9.656and-0.996arelessthanzero.

37

Page 46: MATLAB Short Course

Module3. Files,FunctionsandDataStructures

The fminbnd function finds a minimum valueover an interval; it doesnot necessarilydeterminethe

value(s)of c where d ed c�f�g .Thefminsearch commandfindsthevaluesof thevariableswhichproduceaminimumof amultivariatefunctionbut ratherthanan interval themainargumentto this function is proximity; in otherwordsthisfunction finds the valuesof c , e and h which produceminimum valuesof fn i c�j e j h�k near the valuesc f cEl , e4fme l and h f h l . To determinethe valuesof c , e and h which producethe maximumfunctionalvaluesimply multiply thefunctionby npo beforerunningfminsearch. An applicationof thisfunctionis shown in Example3.5-1(p.147)of Palm. With a little algebraicmanipulation,thetaskcanberesolvedinto a minimisationprobleminvolving a functionof two variablessuchthat q f fn i d j r�k . Thisfunctionis programmedinto a functionfile calledchannel.m andtheargumentsto fminsearch arethenameof the functionandthevaluesof d and r nearwhich the function is to beminimised. The resultis r f4s g °, d�fRt u s g ft. and v f4w�u t t ft. If you have studiedopenchannelhydraulicsyou might recallthatthemostefficient hydraulicsectionfor a trapezoidalchannel(asderivedfrom elementarycalculus)is onewherethehydraulicradius( x ) is half themaximumdepth:

x fyqSf

yv�z|{ d} ~ � r f

o g gw�u t t zR{�� t�u s g} ~ � s g

f���u w g�f t u s g{ f d {

Self-Test 3.3

Palm:T3.5-1 � (p.148)T3.5-2 � (p.149)T3.5-3 (p.149)

3.5 Cellsand Structures

Reading

Palm: Sections3.6- 3.7(pp.149-160)

While standardarraysareusedto storevariablesof the samesizeanddatatype,the cell arrayallowsstorageof differentdatatypesof differentsizes,asshown in Example3.6-1of Palm, whereA(1,1) andA(1,2) arearraysof char(strings)of differentsizes,andA(2,1) andA(2,2) arearraysof double,alsoofdifferentsizes.

Elementsof cell arrayscanalsobearrays.Curly braces� � areusedto assigncells,eitherbycell indexing:

38

Page 47: MATLAB Short Course

3.5. CellsandStructures

mycell(1,1)= � [0:0.1:10] � ;wherethecurly bracesareon theright handsideof theassignmentstatement,or by contentindexing:

mycell � 1,1 � =[0:0.1:10];

wherethecurly bracesareontheleft handside.To retrieveelementsof thearrayin mycell(1,1), thecellindex is usedfirst (in curly braces)followedby thearrayindex (in brackets);for exampleto displaythecontentsof thefirst fiveelementsof thearrayin first row of thefirst columnof mycell, thecommand:

mycell � 1,1 � (1,1:5)

will produce0, 0.1, 0.2, 0.3, 0.4. Notethatcellscanalsobeelementsof cells.Thecelldisp(A) functionprovidesamoredetailedtextualdisplayof thecontentsof thecell arrayA. cellplot(A) providesagraphicdisplay.

Self-Test 3.4

Palm: T3.6-1 � (p.154)

Structuresare perhapsmost useful for storing information in databaseform, as datastoragecan becompartmentalisedaccordingto somelogical hierarchythus facilitating a much easierdataretrieval.Thefieldsof a structurecanbenamedandthusbeaccessedmoreintuitively. Dataareallocatedto fieldsby usingeitherdotnotation:

mystructure.field1=[20 30 40];

or thestruct command:

mystructure=struct(’field1’,[20 30 40];)

Fieldscanalsobenested:

mystructure.field1.subfield1=’John Smith’;

39

Page 48: MATLAB Short Course

Module3. Files,FunctionsandDataStructures

or:

mystructure=struct(’field1’,struct(’subfield1’,’John Smith’))

For examplethe tests field of the student structureshown in the text (p.156)could be arrangedasfollows:

student(1).tests.test1=67; student(1).tests.test2=75; student(1).tests.test3=84;

althoughthis (nestingof fields)methodof datastorageis very inefficient comparedto thearraymethodusedin theexample:

student(1).tests=[67, 75, 84];

Notethedifferencebetweenanarrayof structuresanda structurecomprisingarrays.An arrayof struc-tureshasmorethanoneelementeachwith thesamefieldswhereasa singlestructurehasonly oneele-ment;thefieldsmaybesingle-valued,arraysor nestedcombinationsof eachin eithercase.Thedatatypefor any particularfield in anarrayof structuresdoesnot have to bethesameanddifferentsizescanbeusedfor eachelement.

Self-Test 3.5

Palm:T3.7-1 (p.159)T3.7-2 (p.159)T3.7-3 (p.159)

40

Page 49: MATLAB Short Course

SelfAssessmentQuestions

SelfAssessmentQuestions

3.1 Whatwill betheresultof thefollowing codeenteredon theMATLAB commandline:

a=1:3;dlmwrite(’mydata.out’,a,’,’);type mydata.out

(a) [1, 2, 3]

(b) [1, 1.5, 2, 2.5, 3]

(c) 1, 2, 3

(d) 1;2;3;

(e) noneof theseanswers

3.2 Whatwill betheoutputfrom thefollowing MATLAB code?

ceil(1:0.5:3)

(a) 1, 1.5, 2, 2.5, 3

(b) 1, 1, 2, 2, 3

(c) 1, 2, 3

(d) 1, 2, 2, 3, 3

(e) noneof theseanswers

3.3 Whatwill betheoutputfrom thefollowing MATLAB code?

fix(1:0.5:3)

(a) 1, 1.5, 2, 2.5, 3

(b) 1, 1, 2, 2, 3

(c) 1, 2, 3

(d) 1, 2, 2, 3, 3

(e) noneof theseanswers

41

Page 50: MATLAB Short Course

Module3. Files,FunctionsandDataStructures

3.4 Whatwill betheoutputfrom thefollowing MATLAB code?

floor(1:0.5:3)

(a) 1, 1.5, 2, 2.5, 3

(b) 1, 1, 2, 2, 3

(c) 1, 2, 3

(d) 1, 2, 2, 3, 3

(e) noneof theseanswers

3.5 A complex numbercan be written in rectangularor polar form. The polar form of ���G�J� is��� � �,� � � thecomponentsof whichcanbefoundwith theMATLAB instructions:

(a) abs(3 + 4i); angle(3 + 4i)/(2*pi)*360;

(b) abs(3, 4i); angle(3 + 4i);

(c) abs(3 + 4i); angle(3 + 4i);

(d) abs([3, 4i]); angle(3 + 4i)/(2*pi)*360;

(e) noneof theseanswers

3.6 Whatwill betheoutputfrom thefollowing MATLAB code?

asin(sin(pi/2))*2/pi

(a) 1

(b) 3.1406

(c) 1.5708

(d) 1/2

(e) noneof theseanswers

3.7 Selectthecorrectstatementfor thefollowing MATLAB function:

function myanswer = pressure(rho, g, h)myanswer = rho * g .* h;

(a) thecodemustexist within afile calledmyanswer.m

(b) thevariableg is global

(c) for any scalarvaluesof rho andg thefunctionreturnsanarraythesamesizeash

(d) for any scalarvaluesof g andh thefunctionreturnsanarraythesamesizeasrho

(e) noneof theseanswers

42

Page 51: MATLAB Short Course

SelfAssessmentQuestions

3.8 Giventhefollowing MATLAB function:

function myy = f1(x)myy = 3 * x .ˆ2 + 6 * x + 4;Selectthemostappropriatedescriptionof thevariablemymin resultingfrom thefollowing MAT-LAB code:

y = 0:0.01:4;mymin = fminbnd(’f1’, min(y), max(y));

(a) anarrayof f1(x) valuesover theinterval ���[�"�[�(b) theminimumvalueof f1(x) over theinterval ���[�"�[�(c) thevalueof � where � �� �[� �(d) thevalueof � correspondingto theminimumvalueof f1(x) over theinterval ���[� �[�(e) noneof theseanswers

3.9 Whatis thevalueof thevariablex resultingfrom thefollowing MATLAB instructions:

y= � [2:9],[2, 3, 4], ’John Jones’ �x=[y � 1 � ; y � 2 � ]

(a) [2, 2]

(b) [’J’, ’J’]

(c) [2, 3, 4, 5, 6, 7, 8, 9]

(d) [2, 3, 4, 5, 6, 7, 8, 9]; [2, 3, 4]

(e) noneof theseanswers

3.10 Whatis thevalueof thevariablex resultingfrom thefollowing MATLAB instructions:

student.name = ’John Jones’;student.tests = [11, 22, 33; 44, 55, 66];student(2)=student;x=student(2).tests(2, 1);

(a) [22, 44]

(b) [’J’, ’o’]

(c) 44

(d) 33

(e) noneof theseanswers

43

Page 52: MATLAB Short Course

Module3. Files,FunctionsandDataStructures

Tutorial Problems

Whereappropriate,your model solutionsto the problemsin this and in subsequentModulesshouldincorporateamainscriptfile andoneor morefunctionfiles.

3.1 PalmProblem3.13�3.2 PalmProblem3.15�3.3 PalmProblem3.18�3.4 PalmProblem3.19�

Neglectthecostof thebaseof thetankandassumethatall of theenclosedvolumeof thetankwill befilled

with water. [4.92m, 3.28m]

3.5 PalmProblem3.22� [54.2days]

3.6 A packagingmanufacturerrequiresa programwhich calculatesthe optimumdimensionsof anopenrectangularcartonfor givenvolumesuchthatthesurfaceareaof thecartonis ataminimum.Write a MATLAB programincorporatinga main script andoneor moreuser-definedfunctionsto calculatetheoptimumdimensions.Includethe fminsearch function in theprogram.Usetheprogramto determinetheoptimumdimensionsin millimetresfor a requiredvolumeof onelitre (1litre = 10� mm� ) andconfirmthesolutionby handcalculation. [width 126mm,depth126mm,

height63 mm]

3.7 PalmProblem3.23�3.8 PalmProblem3.24�

Hint: Sketcha layoutfor thecell array(s)first, ensuringthatthearrayhassufficientelementsto caterfor all

combinationsof given � , � , and   values.Cell arraysnestedto two levelsmaybea suitabledesignfor this

problem.

3.9 PalmProblem3.26�Note: An arrayof structuresis required.

3.10 PalmProblem3.27� and3.28�

44

Page 53: MATLAB Short Course

Solutionsto SelfAssessmentQuestions

SelfAssessmentQuestions

Solutions

Table3.1: Solutionsto self assessmentquestions- Module3

Solution Comment

3.1 (c) commadelimited1× 3 array

3.2 (d) ceil roundsup towards ¡3.3 (b) fix roundsdowntowardszero

3.4 (b) floor roundstowardsnearestinteger

3.5 (a) angle returnsanglein radians

3.6 (a) theinversesin of sin(pi/2)is pi/2; whenmultipliedby 2/pi theresultis one

3.7 (c) rho andg mustbescalarvariables,only h canbeanarray

3.8 (d) thereis nochangein thesignof ¢ £¢ ¤ over theinterval given

3.9 (e) x is not assignedasy ¥ 1 ¦ andy ¥ 2 ¦ havedifferentnumberof columns

3.10 (c) first elementof secondrow of tests field

45

Page 54: MATLAB Short Course

Module3. Files,FunctionsandDataStructures

46

Page 55: MATLAB Short Course

Module 4

Programming with MATLAB

4.1 Objectives

Oncompletionof thisModuleyoushouldbeableto:

• applyvariousMATLAB programmingconstructsincludingrelationalandlogical operators,con-ditional statementsandloops,

• designMATLAB programsusingappropriatepseudocodeand/orflowcharts,and

• debug MATLAB programs.

4.2 Relational and Logical Operators

Reading

Palm: Sections4.1- 4.2(pp.167-175)

47

Page 56: MATLAB Short Course

Module4. Programmingwith MATLAB

Therearesix (6) relationaloperatorsasshown in Table4.1-1of Palm. Theseoperatorsyield eitheraone(1) or a zero(0) (indicating true or falserespectively) whentwo variables(or variablearrays) arecompared.Arithmetic operatorshave precedenceover the relationaloperators,but it is alwaysa goodideato usebracketsto improve readability. For example:

a=1:5; a==a.ˆ2;

is moreeasilyreadas:

a=1:5; a==(a.ˆ2);

theresultbeinga1× 5 arrayconsistingof a oneandfour zeros.

Thethree(3) logicaloperatorsareNOT ( § ), AND (&) andOR( ¨ ). TheNOT operatorreturns’true’ (1) ifits argumentis zeroandit returns’f alse’(0) if its argumentis non-zero.TheAND operatorcomparestwovariables;if bothargumentsarenon-zeroit returns’true’ otherwiseit returns’f alse’. TheOR operatoralsocomparestwo variablesandreturns’true’ if at leastoneargumentis non-zeroand’f alse’ if bothargumentsarezero. Thexor function returns’f alse’ if its argumentsareeitherboth zeroor both non-zeroandreturns’true’ if oneof its argumentsis non-zero.Theseareillustratedin thefollowing simpleexamples:

§ 0 = 1 § 3 = 0

0 & 3 = 0 3 & 4 = 1

0 ¨ 3 = 1 3 ¨ 4 = 1

xor(0, 3) = 1 xor(3, 4) = 0

Wherethe argument(s)is (are)an array, the comparisonis madeon an element-by-elementbasiswiththeresultbeinganarrayof thesamesizeasthetwo argumentarrays.

Self-Test 4.1

Palm: T4.2-1 © (p.173)

Notetheuseof relationaloperatorswith thefind functionshown in Example4.2-1of Palm.

48

Page 57: MATLAB Short Course

4.3. ConditionalStatements

4.3 Conditional Statements

Reading

Palm: Section4.3(pp.175-187)

The(if...else...end) or its variantthe(if...elseif...else...end) constructsareperhapsthemosttraditionalconditionalstatementcommonto many high level programminglanguages.Commandswithin the ifblock will be executedsequentiallyif a definedlogical expressionis true, otherwisethe commandswill be skippedastheprogramexecutes.The if blockscanbesequentialor nestedasillustratedin thefollowing exampleof assigningstudentgradesaccordingto totalmarks:

if (marksª =85)grade='HD' ;if (marksª 90)

grade=strcat(grade,'+' );else

grade=strcat(grade,'-' );end

endif(marksª =75 & marks« 85)

grade = 'A' ; 10

if(marksª 80)grade=strcat(grade,'+' );

elsegrade=strcat(grade,'-' );

endendif(marksª =65 & marks« 75)

grade='B' ;if(marksª 70)

grade=strcat(grade,'+' ); 20

elsegrade=strcat(grade,'-' );

endendif(marksª =50 & marks« 65)

grade='C' ;if(marksª 60)

grade=strcat(grade,'+' );else

grade=strcat(grade,'-' ); 30

endendif(marks« 50)

grade='F' ;end

49

Page 58: MATLAB Short Course

Module4. Programmingwith MATLAB

Notethefollowing pointsfrom theprecedingscript:

• Thelogicalexpressionoccursimmediatelyaftertheif statementandis usuallybracketted;thisis toimprovereadabilityonly, MATLAB will notcomplainif thebracketsareomitted,i.e. if(marks ¬ =90)hasthesameeffectasif marks ¬ =90.

• It is goodpracticeto indentthelinesof codewithin eachnestinglevel to improve readabilityandhencefacilitateeasierdebugging; by default the MATLAB editor doesthis automaticallyasthescriptfile is beingedited.

• Thefirst (if...else...end) block occurson lines1-8. If thevalueof thevariablemarks is greaterthanor equalto 85 the programwill enterline 2 of the codeandassigna valueof ’HD’ to thevariablegrade, otherwisetheprogramwill skip to line 9. Line 3 holdsanotherif statementto testwhethermarks exceeds90, hencetherearetwo levels of nestingin thecurrentblock. If it doesexceed90theprogramwill append’+’ to thegradeof ’HD’, otherwise’-’ will beappended.Referto theonline help for thestrcat function (string concatenation)for moreinformation. Note thatthestatementon line 6, grade=strcat(grade,’-’);, will only beexecutedif marks hasa valueofbetween85 and89 inclusive.

• The logical expressionon line 9 containstwo statementsrelatingto theupperandlower boundsof thecutoff marksfor thegradeof ’A’. Wedo notwanttheprogramto enterthis (if...else...end)block unlessthevalueof thevariablemarks is in therange75 - 84.

• Notethatif thevalueof marks is lessthan50,only theline of codewith thecommandgrade=’F’;will beexecuted.

• This particularapplicationof conditionalexpressionsandsubsequentassignmentof variablescanbeimplementedmuchmoresuccinctlywith a loopconstructasweshallseelater.

4.4 Program Designand Documentation

Takeparticularnoteof thematerialonpp.177- 179of Palm. Eventheexperiencedprogrammerneedstotake thetime to designa suitableprogramstructurebeforeattemptingto write any codeof significance.Largeprogramsespeciallyneedto bemodular;it is mucheasierto designa solutionto a largecomplexproblemby subdividing theprobleminto aseriesof smallsimpletasks;hencetheinclusionof functionsis of primary importancein the designof programstructure.Ideally the main MATLAB script shouldserveonly to controlthe’flow’ of operationsin theprogramby callingaseriesof functionsto implementintermediatetasks.For this reasonthestructure chart, an exampleof which is shown asFig. 4.3-3ofPalm,is animportantpre-requisitefor goodprogramming.Oncethestructureof theprogramis decided,thedevelopmentof pseudocodeand/orflowchartsareinvaluabledesignaidsfor formulatingthecodetoimplementthetaskof eachfunction,aswell asthemaincalling script. For examplea suitablestructurechartfor thestudentgradingprogrammight beasshown in Figure4.1below.

50

Page 59: MATLAB Short Course

4.4. ProgramDesignandDocumentation

GRADER.Mmainprogram

READDB.Mreadstudentdetailsfrom databasefile

ENTERMK.Mentermarks

from keyboard

ENTERCUT.Mentergradingcutoff marks

from keyboard

CALCGRD.Mcalculategrades

PRTRPT.Mprint report

Figure4.1: Structurechartfor studentgradingprogram

Under this structurethe main script (GRADER.M) would call the functionsREADDB, ENTERMK,ENTERCUT, and PRTRPT sequentially, and the function ENTERCUT would call CALCGRD. Thestudentdatabasecouldbestoredasa globalarrayof structures,with eachsequentialfunctionupdatingand/oroutputtingtherequiredfieldsof thestructurearray. An exampleof pseudocodewhich might beappropriatefor theENTERCUTandCALCGRDfunctionscouldbe:

ENTERCUT.Mreadgradingcutoffs from keyboard(cutoff1, cutoff2, cutoff3 etc.);call CALCGRDpassingthecutoffs asarguments;

CALCGRD.Mfor eachstudentin thedatabase:

if (marksgreaterthanor equalto cutoff1)assignan’HD’ grade;

elseif(marksgreaterthanor equalto cutoff2)assignan’A’ grade;

elseif(marksgreaterthanor equalto cutoff3)assigna ’B’ grade;

elseif(marksgreaterthanor equalto cutoff4)assigna ’C’ grade;

elseassignan’F’ grade;

endend

51

Page 60: MATLAB Short Course

Module4. Programmingwith MATLAB

Self-Test 4.2

Palm: T4.3-2 ­ (p.185)

Hint: Plot the functionalrelationshipof sin(® ) against® first thenwrite the algorithmin pseudocodebeforeat-

temptingto encodeit. Usethe(if...elseif...else...end) constructor its variationsandtheerror command.

4.5 Loops

Reading

Palm: Sections4.4- 4.5(pp.187-201)

Loopsareconstructsin whichtheenclosedcommandsareexecutedrepetitively. The(for...end) constructexecutesthe loop a predefinednumberof times,whereasthe (while...end) block continuesexecutionuntil a certainconditionis satisfied;i.e. thenumberof iterationsis not necessarilyknown in advance.Theseconstructsareknown asexplicit loops,in contrastto implicit loopsasdescribedonp.191of Palm.BecauseMATLAB is designedspecificallyfor matrix operations(i.e. the default datatypeis an arrayratherthana single-valuedvariable),the computationalalgorithmsusedin MATLAB aremuchmoreefficient with implicit thanfor explicit loops. Thegoldenrule for programmingin MATLAB is to useimplicit loopswherever possibleasthecomputationalspeedis ordersor magnitudefasterthanthat forexplicit loops.

For exampleconsiderthe following script which assignsthirty thousandelementsto the vector ¯ andthencalculatesvector ° of thesamesizesuchthat °=±�² ¯E³�´Kµ ¯E¶�´�· ¸ ¯�´[² in threeways;thefirst twousingexplicit (FORandWHILE) loopsandthe third usingan implicit loop utilising MATLAB matrixalgebra:

% LOOPTEST.M compares speedof explicit and implicit loops% for calculating 3rd order polynomialclear;clc;% set huge arrayx=[0:3e4];%

52

Page 61: MATLAB Short Course

4.5. Loops

% start timer for explicit (FOR) loopstime=cputime;for(k=1:length(x)) 10

y(k)=2 ¹ x(k)ˆ 3+4 ¹ x(k)ˆ 2+10 ¹ x(k)+2;end% stop timerftime=cputime;fprintf('\nCPU time for explicit (FOR) loop was %.1f seconds.' ,ftimeº stime);% clear all variables from memoryclear;x=[0:3e4];%% start timer for explicit (WHILE) loop 20

stime=cputime;k=1;while(k» =length(x))

y(k)=2 ¹ x(k)ˆ 3+4 ¹ x(k)ˆ 2+10 ¹ x(k)+2;k=k+1;

end% stop timerftime=cputime;fprintf('\nCPU time for explicit (WHILE) loop was %.1f seconds.' ,ftimeº stime);% clear all variables from memory 30

clear;x=[0:3e4];%% start timer for implicit loopstime=cputime;y=2 ¹ x.ˆ 3+4 ¹ x.ˆ 2+10 ¹ x+2;ftime=cputime;fprintf('\nCPU time for implicit loop was %.3f seconds.\n' ,ftimeº stime);% EOF

40

Theoutputfrom theMATLAB commandwindow is asfollows:

looptest

CPU time for explicit (FOR) loop was 47.6 seconds.CPU time for explicit (WHILE) loop was 48.3 seconds.CPU time for implicit loop was 0.030 seconds.diary off

Thedifferencein computationalefficiency is quitedramatic!

53

Page 62: MATLAB Short Course

Module4. Programmingwith MATLAB

Self-Test 4.3

Palm:T4.4-1 (p.192)T4.4-3 ¼ (p.199)T4.4-4 ¼ (p.199)

Note: Write suitablepseudocodebeforeattemptingto encodethelastproblem.

The (switch...case...otherwise...end) constructis anotherconditional block statementwhere onlythosecommandsfor which a particularlogical expressionis true areexecuted. It differs from the ifstructurein thatoncethefirst case expressionis foundto betrue,only thosestatementsinsidethatpar-ticular case block areexecuted;theremainingcase statementsarenot tested.Thefollowing providesanexampleof theswitch constructusingthestudentgradingproblempreviously outlinedon p.50.

cutoffs½ 1,1 ¾ =[91:100]; cutoffs½ 1,2 ¾ ='HD+' ;cutoffs½ 2,1 ¾ =[85:90]; cutoffs½ 2,2 ¾ ='HD-' ;cutoffs½ 3,1 ¾ =[81:84]; cutoffs½ 3,2 ¾ ='A+' ;cutoffs½ 4,1 ¾ =[75:80]; cutoffs½ 4,2 ¾ ='A-' ;cutoffs½ 5,1 ¾ =[71:74]; cutoffs½ 5,2 ¾ ='B+' ;cutoffs½ 6,1 ¾ =[65:70]; cutoffs½ 6,2 ¾ ='B-' ;cutoffs½ 7,1 ¾ =[61:64]; cutoffs½ 7,2 ¾ ='C+' ;cutoffs½ 8,1 ¾ =[50:60]; cutoffs½ 8,2 ¾ ='C-' ;switch(0)caseisempty(find(cutoffs½ 1 ¾ ==marks)) 10

grade=cutoffs½ 1,2 ¾ ;caseisempty(find(cutoffs½ 2 ¾ ==marks))

grade=cutoffs½ 2,2 ¾ ;caseisempty(find(cutoffs½ 3 ¾ ==marks))

grade=cutoffs½ 3,2 ¾ ;caseisempty(find(cutoffs½ 4 ¾ ==marks))

grade=cutoffs½ 4,2 ¾ ;caseisempty(find(cutoffs½ 5 ¾ ==marks))

grade=cutoffs½ 5,2 ¾ ;caseisempty(find(cutoffs½ 6 ¾ ==marks)) 20

grade=cutoffs½ 6,2 ¾ ;caseisempty(find(cutoffs½ 7 ¾ ==marks))

grade=cutoffs½ 7,2 ¾ ;caseisempty(find(cutoffs½ 8 ¾ ==marks))

grade=cutoffs½ 8,2 ¾ ;otherwise

grade='F' ;end

54

Page 63: MATLAB Short Course

4.5. Loops

In thisexamplethegradingcutoffs aredefinedin thefirst columnof acell array(why notuseastandardnumericalarray?1) andthecorrespondinggradesarestoredin thesecondcolumnof thecell array. Theconditionaltestwill beappliedto theexpressionimmediatelyafterthewordswitch; in thiscaseit is zerohencetheexpressionsimmediatelyfollowing eachcase statementwill betestedto determinewhich oftheseis equalto zero,andthecommandswithin thefirst case block which satisfiesthis conditionwillbeexecuted.If noneof thecase expressionsequalszero,controlwill revert to theotherwise block.

Now considerthefirst case expressioncase isempty(find(cutoffs ¿ 1 À ==marks)) andtry to decipherthealgorithm. The inner statementfind(cutoffs ¿ 1 À ==marks) will determinethe index of theelementin thenumericalarrayin thefirst row (andfirst column)of thecutoffs cell arraywhich is equalto thevariablemarks. If a matchis found thenfind will returna number(the index) otherwiseit will returnnothing. If it returnsa numberthe expressionisempty(find(cutoffs ¿ 1 À ==marks)) will be false(i.e.equalto zero); if find returnsnothingthe sameexpressionwill be true (i.e equalto one). If the valueof isempty(find(cutoffs ¿ 1 À ==marks)) is falsethenthevariablemarks is anelementof thenumericalarrayin thefirst row of thecutoffs cell arrayandthefollowing statementgrade=cutoffs ¿ 1,2 À ; will beexecutedandtheprogramwill thendropoutof theswitch block. Thevariablecutoffs ¿ 1,2 À is thegrade(string)associatedwith thenumericalarrayin thefirst row of thecell array.

Thesameoperationcanbedonemoresuccinctlyusinga loop:

cutoffsÁ 1,1 Â =[91:100]; cutoffsÁ 1,2 Â ='HD+' ;cutoffsÁ 2,1 Â =[85:90]; cutoffsÁ 2,2 Â ='HD-' ;cutoffsÁ 3,1 Â =[81:84]; cutoffsÁ 3,2 Â ='A+' ;cutoffsÁ 4,1 Â =[75:80]; cutoffsÁ 4,2 Â ='A-' ;cutoffsÁ 5,1 Â =[71:74]; cutoffsÁ 5,2 Â ='B+' ;cutoffsÁ 6,1 Â =[65:70]; cutoffsÁ 6,2 Â ='B-' ;cutoffsÁ 7,1 Â =[61:64]; cutoffsÁ 7,2 Â ='C+' ;cutoffsÁ 8,1 Â =[50:60]; cutoffsÁ 8,2 Â ='C-' ;cutoffsÁ 9,1 Â =[0:49]; cutoffsÁ 9,2 Â ='F' ;k=1; 10

while(k à =length(cutoffs))switch(0)caseisempty(find(cutoffsÁ k  ==marks))

grade=cutoffsÁ k,2 Â ;endk=k+1;

end

In this casewe cannotusethesameotherwise statementbecausetheloop performstheconditionaltestsequentially. For exampleif thevariablemarks is equalto 91, thena matchwill not be found on thelastpass( Ä Å4Æ ) of the loop asthematchingvalueis in fact in thefirst row ( Ä ÅSÇ ) of thecell array;asimilar otherwise statementherewould erroneouslychangethegradefrom ’HD+’ to ’F’. Theremedyto this problemis to expandthecell arrayto explicitly includeelementsassociatedwith the ’F’ grade.Notethatin bothexamplestheinput variablemarks mustbeaninteger.

1Becausethecutoff rangesaresuchthatthereis not thesamenumberof columnsin eachrow.

55

Page 64: MATLAB Short Course

Module4. Programmingwith MATLAB

4.6 Debugging

Reading

Palm: Section4.6(pp.201-208)

Debuggingis an importantpart of programming.It is very rareeven for the experiencedprogrammerto createa pieceof codewhich works to expectationon the first attempt. Syntaxerrorsaregenerallymucheasierto locateandrectify asMATLAB will respondwith theappropriateerrormessage,whereasruntimeerrorscanbea little moredifficult to detect.TheMATLAB programhasa inbuilt Debugger toassistin locatingthesemoredifficult typesof errors.Perhapsthebestway to learnto usethis facility isby following theexamplein thetext.

Createthe two function files FUN1.M andFUN2.M asdescribedthe reading(p.205)andexecutetheprogramby enteringfun1([1, 2, 3, 4, 10]) on theMATLAB commandline. Theresultis 3 which weknow to be incorrect.Now displayall threewindows (theMATLAB commandwindow, theMATLABeditor window for FUN1.M and the MATLAB editor window for FUN2.M) using the menuView -Dock FUN1.M on the first editor window andView - Dock FUN2.M on the secondeditor window.Setthecursorto the line y=fun2(avg,x) by left-clicking anywhereon the line in theeditorwindow forFUN1.M, andthenseta breakpointfor this line by left-clicking on the’reddot’ icon in theuppermenuof the samewindow. A red dot shouldappearon this line indicatingthat a breakpointhasbeensetatthis location. Now executetheprogramby repeatingthecommandfun1([1, 2, 3, 4, 10]) in themaincommandwindow. Checkthevalueof thevariableavg by firstly highlighting2 thewordavg on the’reddot’ line of FUN1.M andthenright-clickingonthehighlightedwordandselectingEvaluate Selection.Thevalueof thevariableavg will bedisplayedin themaincommandwindow. In this casetheanswer(4) is correctso theerrormustlie in thesubsequentlinesof codeandfurther investigationis required.Clearthepreviousbreakpointby placingthecursoronthe’reddot’ line of FUN1.M andleft-clicking thesame’reddot’ icon from themenuandallow theprogramto terminateby clicking the’down arrow’ iconfrom thesamemenu.Now setabreakpointon theline function above = fun2(x,avg) in theMATLABeditorwindow for FUN2.M, executethemainprogramasbeforeandevaluatethevariablesx andthenavg. TheMATLAB commandwindow indicatestheresultthatx = 4 andavg = [1, 2, 3, 4, 10] whichisobviouslyincorrectandthereinliestheerror;theorderof thevariablespassedfromFUN1.M to FUN2.Mis incorrectandtheline y=fun2(avg,x) in FUN1.m shouldready=fun2(x,avg).

The Debugger is particularlyusefulfor loops. Run throughthesubsequentexampleon p.208-209ofPalmandtake noteof theoutputusingtheStep facility in theeditorwindow for INVEST.M.

2A word maybehighlightedby holdingdown theleft mousebuttonanddraggingacrossthewindow until thewholewordis highlighted(in blueby default).

56

Page 65: MATLAB Short Course

SelfAssessmentQuestions

SelfAssessmentQuestions

4.1 Whatwill betheoutputfrom thefollowing MATLAB code?

a=[3:7]; b=[2:2:10]; a(find(a==b))

(a) 2, 4

(b) 2

(c) 4

(d) 10

(e) noneof theseanswers

4.2 Whatwill betheoutputfrom thefollowing MATLAB code?

a=[3:7]; b=[2:2:10]; b(a È b)

(a) 2, 4

(b) 2

(c) 4

(d) 10

(e) noneof theseanswers

4.3 Whatwill betheoutputfrom thefollowing MATLAB code?

a=[3:7]; b=[2:2:10]; a(b==sum( É a+2))

(a) 2, 4

(b) 2

(c) 4

(d) 10

(e) noneof theseanswers

57

Page 66: MATLAB Short Course

Module4. Programmingwith MATLAB

4.4 Whatwill betheoutputfrom thefollowing MATLAB code?

a=[3:7]; b=[2:2:10]; sum((a&b)+(a Ê b))

(a) 2, 4

(b) 2

(c) 4

(d) 10

(e) noneof theseanswers

4.5 MATLAB codeis requiredto allocateagradingaccordingto thefollowing scheme:

score grading

6 -10 high

1 - 5 low

zero nil

Whatalterationsarerequiredto the following function in orderto implementthis algorithmcor-rectly?

function thisgrade=grading(score)if (score Ë�Ì 10)

grading=’high’;elseif (score ËpÌ 5)

grading=’low’;else

grading=’nil’;end

(a) includetheadditionalcondition(& score Í 5) in thesecondline

(b) includetheadditionalcondition( Ê score) in thefourth line

(c) includetheadditionalcondition(& score) in thefourth line

(d) includebothitems4.5 (a) and4.5 (b)

(e) noneof theseanswers

58

Page 67: MATLAB Short Course

SelfAssessmentQuestions

4.6 How many passeswill bemadeby thefollowing MATLAB loop:

a=[1:5];while(a)

x=aˆ2;a=a+1;

end

(a) Î(b) 5

(c) 1

(d) 0

(e) noneof theseanswers

4.7 How many passeswill bemadeby thefollowing MATLAB loop:

a=[1:5];while(a)

x=aˆ2;a=a-1;

end

(a) Î(b) 5

(c) 1

(d) 0

(e) noneof theseanswers

59

Page 68: MATLAB Short Course

Module4. Programmingwith MATLAB

4.8 How many passeswill bemadeby thefollowing MATLAB loop:

a=[1:5];while(x)

x=aˆ2;a=a+1;

end

(a) Ï(b) 5

(c) 1

(d) 0

(e) noneof theseanswers

4.9 With whichsinglestatementcouldthefollowing MATLAB functionbereplaced:

function return1=test1(x)return1=0;for(k=1:length(x))

x(k)=x(k)ˆ2;return1=return1+x(k);

end

(a) sum(xˆ2)

(b) sum(x)

(c) factorial(x)

(d) sum(x.ˆ2)

(e) noneof theseanswers

60

Page 69: MATLAB Short Course

TutorialProblems

4.10 For which valuesof thescalarvariablex will thefollowing MATLAB functionassigna non-zerovalueto thereturnvariablereturn1:

function return1=test1(x)return1=0;switch(x)case Ð x

return1=x;case x Ñ 0

break;case(isempty(x))

return1=1/x;otherwise

return1=1-x;end

(a) Ò�Ó4Ô(b) ÒKÕÓ4Ô(c) Ò�Ó�Ö(d) Ò ×�Ö(e) noneof theseanswers

Tutorial Problems

4.1 PalmProblem4.10Ø4.2 PalmProblem4.14Ø4.3 PalmProblem4.17Ø4.4 PalmProblem4.18Ø

Hint: usethe fminsearch function andconsultthe MATLAB online help for assistancewith syntaxre-

gardingthesurf andcontour plotting functions. [ Ù�Ú"Û , ÜpÚ[Ý Þ ; lessthan2%variationin cost]

4.5 PalmProblem4.21ØNote: Interestis creditedonly on theamountheldin theaccountfor theprecedingtwelvemonths.

4.6 PalmProblem4.23ØHint: A methodincorporatingthesolutionof simultaneousequationsusingthe left division operatormay

beappropriatefor this problem.

4.7 PalmProblem4.25ØHint: usetheMATLAB onlinehelpfor assistancewith themesh andcontour plotting functions.Assume

thatthegivenboundarytemperatureßJà appliesover theentirelengthof theupperboundary.

[2 termsrequired,centretemperature102.5á F]

61

Page 70: MATLAB Short Course

Module4. Programmingwith MATLAB

4.8 PalmProblem4.26â4.9 PalmProblem4.28â

4.10 PalmProblem4.34âSelfAssessmentQuestions

Solutions

Table4.1: Solutionsto self assessmentquestions- Module4

Solution Comment

4.1 (c) a==b returns0,1,0,0,0 anda(2) is 4

4.2 (b) a ã b returns1,0,0,0,0 andb(1) is 2

4.3 (e) ä a returnsfive zeros; ä a+2 returnsfive twos, the sumof which is ten; ten is the fifthelementof b anda(5) is 7

4.4 (d) a&b anda å b eachreturnfivesones,thesumtotalof which is ten

4.5 (e) both4.5 (a)and4.5 (c) required

4.6 (a) asa is alwaysnon-zerotheloop is infinite

4.7 (c) afterthefirst passthefirst elementof a will bezeroandtheloopwill terminate

4.8 (d) will terminatewith anerrormessageasx hasnot beenassigneda value

4.9 (d) thefunctiondeterminesthesumof thesquaresof theelementsof vectorx

4.10 (b) thefirstandthird case expressionscanneverbeinvokedfor any valueof x; theseconddoesnothing;only theotherwise expressioncanchangereturn1 but only whenx is otherthanunity

62

Page 71: MATLAB Short Course

Module 5

Plotting and Model Building

5.1 Objectives

Oncompletionof thisModuleyoushouldbeableto:

• createvarious two and three-dimensionalplots including line, scatter, stem, bar, logarithmic,semilogarithmic,polar, surfaceandcontourgraphs,overlayplotsandsubplots,

• annotateelementsof graphsincludingaxislabels,titles, tickmarks,line andmarkersymbols,grid-lines,TEX text symbolsandlegends,

• exportgraphsin variouselectronicgraphicsformats,and,

• designlinearandnon-linearregressionmodelsof data.

5.2 Plotting Functions

Reading

Palm: Sections5.1- 5.4(pp.229-262)

63

Page 72: MATLAB Short Course

Module5. PlottingandModelBuilding

Thematerialin this sectionof the text explainsin greaterdetail theplotting functionswe have alreadyusedin previous Modules,but also introducessomenew inbuilt functionsrelating to plotting. Takeparticularnoteof thefollowing describedin thefirst partof thereading:

• theaxis command,

• thesyntaxof theplot commandto plot complex numbers,and

• the fplot commandfor plotting functions.

Subplotsis the namegiven to multiple plots producedin the samegraphicswindow. subplot(m,n,p)splits thecurrentgraphicswindow into m× n sub-windows with æ rows and ç columns,anddraws theoutputfrom subsequentplotting commandsin the è�é ê sub-window, which is countedrow-wisefrom thetop left of themainwindow. An overlayplot is onein which multiple seriesof dataareplottedon thesamegraph.

Table 5.2-1 of Palm lists the codesfor variousline and marker typesand colours. For examplethecommandplot(x,y1,’rx’,x,y2,’g-’); will createatwo-dimensionaloverlayplotusingaredcrossfor markersymbolsfor the first series(ëEì againstí ), plottedasa scattergraph,anda greenline for the secondseries(ë�î againstí ), which will bedisplayedasa continuousline graph. Much greatercontrolof lineandmarker size,shapeandcolourcanbeattainedby specifyingline andmarker propertiesasoptionalarguments,for examplethecommand:

plot(x,y,’:rs’,’LineWidth’,2,’MarkerEdgeColor’,’k’,’MarkerFaceColor’,’g’,’MarkerSize’,10);

will createa plot incorporatinga reddottedline, two printer’s points1 thick, connectingsquaremarkerseachtenpointshighwith blackedgesandgreenfaces.

Alternatively an overlay plot canbe drawn usingsequentialcalls of the plot commandwith the holdcommand;e.g. plot(x,y1,’rx’); hold on; plot(x,y2,’g-’);. The legend function addsa legendto themultiple seriesplot usingtheuser-suppliedstringarguments.Theorderof thesestringsshouldbesameastheorderof eachseriesgivenastheplot arguments.

Thetext functiondrawstextualannotationsontheplot atauser-definedlocation.MATLAB incorporateselementsof theTEX typesettinglanguageto enableplots to beannotatedwith Greekandmathematicalsymbols,aswell as superscriptsandsubscripts.The completeset of supportedTEX symbolscanbefoundby searchingtheMATLAB onlinehelp index for ’TeX’. For example,to producetheannotationï ðñ*ò�ó�ô õ ö ÷ ø

ona plot at thelocation ù í ò ì ú ë ò�û�ü in a12 point font, thesyntaxis:

text(1,3,’ ý thetaˆ2 1 = aˆ þ eˆ þ cos ý alpha ÿ ÿ ’,’FontSize’,12);

Othertext propertiescanbevariedasrequired;for examplethecommand:

xlabel(’xname’,’FontSize’,15,’FontName’,’Courier’,’FontAngle’,’oblique’,’FontWeight’,’bold’);

1A printer’s point is a unit of length. Thereare72 printer’s points in oneinch so a printer’s point is equivalent to about350� m. Thedefault line width in MATLAB is 0.5pointsandthedefault marker sizeis 6 points.

64

Page 73: MATLAB Short Course

5.2. PlottingFunctions

will draw the given horizontalaxis label in a 15 point, bold, italic (oblique)Courierfont. ConsulttheMATLAB onlinehelpfor moreinformationonaxes, figure, line andtext properties.For example,axespropertiescanbechangedwith constructslike:

set(gca,’XTick’,[0:0.1:1],’LineWidth’,1.5,’TickDir’,’out’);

which setsthe ticks and labelsfor the � axis at intervals of 0.1 over the rangezero to one, setstheline width of the � and � axes at 1.5 points, anddraws the tick marksout from the axis lines. Theaxislabelscanbechangedby changingtheXTicklabel andYTicklabel fieldsof theaxes structure.Todisplaythefieldsof theaxes structureandtheir currentvalues,usetheMATLAB commandget(gca)after initiating theplotting routine(gca is thecommandacronym for get currentaxes). For thefigurestructureuseget(gcf) (get current figure) to displayfields andcurrentvaluesafter drawing the figurewindow. For examplethe commandh=get(gca) following a plot or similar commandwill copy thecurrentaxes structureto thevariableh, so that theexpressionh.GridLineStyle might yield a resultof(:), which is the symbol representinga dottedline, the default style for gridlines in MATLAB. ThusGridLineStyle is a predefinedfield of theaxes structure,asareXTick, LineWidth, XTicklabel, etc.asdemonstratedabove.

The hold function is particularly useful for ’animating’ plots, wherefor example,we might want tovisualisethe responseof anengineeringsystemto a seriesof inputsover time. By placingtheplottingroutinein a loopwhereeachpassrepresentsincrementaltimesteps,it is possibleto overlayeachplot toshow how theresponsechangesfor subsequenttimesteps.

Theloglog functionplotsthe � and� databothonlogarithmicscales.semilogx drawsasemilog graphinwhichthehorizontalaxisis logarithmicandtheverticalaxislinear. semilogy doesthereverse.Example5.3-1 in the text shows an applicationwhich plots the behaviour of a low-passfilter involving a log-log plot wheretheabscissarepresentsthe imaginarypartof thevoltagefrequency andtheordinatetheamplituderatio.

The Plot Editor describedin Section5.4 of the text provides a graphicalinterface for changingtheappearanceof graphscreatedwith MATLAB, however the samefunctionality can be achieved withcommandline instructionssuchasthosedescribedabove. You mayinvestigatethePlot Editor furtherifyou think it couldbeusefulbut this is a matterof preference;mostprogrammerswould probablypreferusingcommandline instructionsasthesecanbeeasilyencodedin a script file precludingtheneedforany userinput at runtime.

Self-Test 5.1

Palm:T5.3-1 (p.258)T5.3-2 (p.259)T5.3-3 (p.259)

65

Page 74: MATLAB Short Course

Module5. PlottingandModelBuilding

5.3 Function Discovery

Reading

Palm: Sections5.5- 5.7(pp.262-296)

This sectionis concernedwith finding algebraicrelationshipsamongdata.Many engineeringinvestiga-tionsrequirethatwe undertake a seriesof measurementson somestructureor device,particularlywhenthebehaviour of thesystemis notwell known or understoodandnoready’recipe’is availableto forecastthelikely responseof thesystemwith any confidence.By measuringtheresponseof amodelof asystemto a seriesof inputsit maybepossibleto developanalgebraicrelationshipbetweeninput andresponsewhichwill enableusto confidentlypredicttheresponseof a largerprototypeof asimilarsystemwithouttheneedto testit.

As describedin thetext therelationshipbetweeninputandresponsefor mostof thecommonengineeringsystemswill be either linear, poweror exponentialin form, or somecombinationof thesethreebasictypes. A linear systemis onefor which (for example)a doublingof the input resultsin a doublingoftheresponse.A systemwhich follows a power relationshipsuchas ����� � will besuchthatanincreasein theinput by a factorof two will increasetheresponseby a factorof eight( � �� ). Most non-linearsystemscanbereducedto a linearsystemof theform � ��������� by applyingsimpletransformationsasshown in the text. For examplea power systemcanbe transformedinto a linear systemby takingthelogarithmsof themeasuredinput andresponsedataanda log-log plot of responseagainstinput willform astraightline with slope� andintercept� . A systemof theexponentialform will transformintoalinearoneby takingthelogsof theresponsedataandasemilogplot of responseagainstinputwill formastraightline.

The MATLAB polyfit function canbe usedto determinethe slopeandinterceptof the line of bestfitof the input andresponsedata,transformedasnecessary. The line of bestfit is the linear relationship����������� whichminimisestheerror(morecorrectlythesumof squareserrors or SSE)betweentheobservedresponseandthederivedalgebraicrelationship.In equationform:

SSE � ��� ��� � � pred ��� � meas� �! where� meas is themeasuredresponseand � pred is theresponsepredictedby thealgebraicrelationship.The differencebetweeneachof theseelementsis squaredto eliminatenegative numberswhich wouldotherwisebias the summation. One of the objectives thereforein deriving an algebraicrelationshipbetweeninput andresponseis to minimiseSSEbetweenthemeasuredandthepredictedresponse.Notethatthetext uses’ " value’ for SSE.

66

Page 75: MATLAB Short Course

5.3. FunctionDiscovery

Example5.5-1of thetext showstheuseof polyfit to determinetheline of bestfit of alinearsystem.Oncethedataareenteredinto theMATLAB workspace,thecommandpolyfit(force,deflection,1) fits apoly-nomialof degreeoneto thedata;thecoefficientsof thepolynomialbeingcalculatedsuchthatSSEis ataminimum.A polynomialof degreeoneis of theform # $�%�&�'�( hencethecoefficientvectorreturnedby polyfit will containtwo elements,% and ( . In this casethevectorp is [0.0009267, -0.001778]which meansthat the slopeof the line of bestfit is )!* ) ) ) + , - . inches/poundandthe intercepton theordinateaxis is /0)1* ) )!2 . . 3 inches.Notethevalueof 2 ) . + givenin theexampleis thereciprocalof thisslope;i.e theslopeof theline of bestfit of forceagainstdeflectionis 2 4 )!* ) ) ) + , - .5$�2 )1. + pounds/inch;thecantilever’s springconstant.Thesumof squareserrorsfor thisexamplecanbedeterminedfrom:

sse=sum((deflection-polyval(p,force)).ˆ2);

which in thiscaseequals-!* , ,5672 )18:9 squareinches.

Example5.5-2givesan exampleof fitting to a non-linearsystem.From examinationof the respectiverectilinearandsemilogplots, it is determinedthat the systemcanbestbe describedby an exponentialform: ; / ; < $=(>6�2 ) ?�@

takinglogs: A B CED ; / ; < F $=A B CG(�'HA B C5I 2 ) ?J@ K$=A B CG(�'H%�Lsothata plot of A B CED ; / ; < F (relative temperature)againstL (time) will form a straightline of slope %andinterceptA B CM( . The instructionp=polyfit(time,log10(reltemp),1); determinestheequationof theline of bestfit suchthatp(1) $�% andp(2) $�A B CM( . Thetime requiredto cool to 120N F canbefoundby rearrangingthepreviousequation:A B CED ; / ; < F $=A B CM(�'O%�LLP$ A B CED ; / ; < F /OA B CM(% $ A B CED 2 , )J/7- 3 F /7A B CG(%Theusehereof relativeratherthanactualtemperatureis importantasit forcesthealgebraicrelationshipof temperatureagainsttime on a rectilinearplot to be asymptoticto the abscissaaxis; i.e. D ; / ; < Fwill approachzeroas L approachesinfinity andif a valueof

;lessthan

; < is input into the previousequation,theresultwill be imaginary;i.e. no realsolutionwill exist accordingto thederivedalgebraicrelationship.If actualtemperaturesareusedto fit thedata,thefitted equationwill erroneouslypredictarealsolutionfor L when

;�Q�; < . This is oneof thepitfalls of extrapolationasoutlinedin thetext; thereis no guaranteethat thederivedalgebraicrelationshipbetweeninput andresponsewill bevalid outsidetherangeof themeasurementsusedin fitting. In this examplethederivedalgebraicrelationship(basedoneitherrelativeor actualtemperatures)wouldforecastanincorrectvaluefor L if weinputatemperatureof lessthan68N F.

67

Page 76: MATLAB Short Course

Module5. PlottingandModelBuilding

In Example5.5-3it is postulatedfrom theoreticalconsiderationsthat theflowrateout of thecoffeepotwill be a power function of the volume inside the coffee pot, thus a log-log plot of flowrate againstvolumeshouldform astraightline: RTSVU1WYXZ

takinglogs: [ \ ] RTS [ \ ] U0^ [ \ ]W_

which is of theform [ \ ] RYS�` [ \ ] WO^Ya where

bSdce and

a S [ \ ] U . In otherwordsthedatashouldplot asastraightline onthelog-logplot of

Ragainst

Wwith aslopeof

ce andanintercepton theordinateaxisof [ \ ] U . Thecalculatedvalueof

`fS�g1h i j jfrom thepolyfit functionis in fair agreementwith the

theoreticalvaluewhile thecalculatedvalueof

a S�g!h g i k kis known asanempirical2 constant.

Theseexamplesrelatingto thediscovery of algebraicrelationshipsbetweeninput andresponsefollow aprincipleknown asregression. A regressionof responseon input producesanalgebraicrelationshipbe-tweeninput andresponsewhichminimisesSSEbetweenthemeasuredandthepredictedresponse.Thisis theso-calledleastsquaresmethodasdescribedin thetext. Do not beconcernedwith themechanicsof partialdifferentialcalculususedin thederivationof thecoefficientsof theline of bestfit asyou willgainmorefamiliarity with this topic in othercourses.Suffice to sayat this stagethat theminimumof afunction(in this casethefunctionis SSEor ’ l value’) with respectto aninput variableof that functionoccurswhenthefirst derivative of thefunctionwith respectto thatvariableis equalto zero.

Thefunctionalityof thepolyfit commandis not limited to linear (or transformedlinear)algebraicrela-tionshipsasillustratedin thetext, but beawareof thedangersof ’overfitting’ thealgebraicrelationship.For examplethefifth-degreepolynomialshown in Fig. 5.6-4in the text providesanexcellentfit to theobserved response,but is it a ’reasonable’predictorof how you would intuitively expectthesystemtobehave?

While theSSEprovidesacomparativemeasureof thegoodnessof fit of thealgebraicexpressionwith theobservedresponse,amoreuniversal(dimensionless)measureis thecoefficientof determinationm U e n . Ingeneralthedeviationbetweenthemeasuredandthepredictedresponseismadeof of twocomponents;thesumof squareserrors(SSE)representsthecomponentwhich cannotbeaccountedfor by theregressionandthesumof squaresregression(SSR)is thecomponentwhich is accountedfor by theregression.Thetotaldeviation (alsocalledthesumof squarestotal or SST)is thesumof thesetwo:

SST

SSSE SSR

where SSE

Spoqr s cut v pred r0w v measr x e (aspreviously defined)

SSR

Spoqr s cut v pred r0w v measx e

SST

Spoqr s c:y v measr w v measz e2Empiricalmeansderivedfrom experiment;i.e. withoutnecessarilyhaving any physicalsignificance.

68

Page 77: MATLAB Short Course

5.3. FunctionDiscovery

where{ meas |}~� ���E� { meas� �� is theaveragevalueof themeasuredresponse.Thecoefficient of deter-

minationmaybedefinedastheratioof theexplaineddeviation to thetotaldeviation:� � | SSRSST

but SSR | SST � SSE

so � � | SST � SSESST |�� � SSE

SST

which is the sameas Eqn. 5.6-3 in the text, substitutingSSEfor ’ � value’ and SST for ’ � value’.� � thereforeprovidesa non-dimensionalmeasureof the goodnessof fit. If all of the deviation canbeexplainedby theregressionthenSSR= SST, SSE= 0 and � � |�� , which indicatesa perfectfit. If noneof thedeviation canbe explainedby the regressionthenSSR= 0, SSE= SSTand � � |>� , suggestingthereis no relationshipwhatsoever betweenthealgebraicexpressionandthemeasuredresponse.

The text describesthe problemsassociatedwith numericalprecisionin determiningthecoefficientsofthefitted equation;thesecanbecomequitesignificantfor ’overfitted’ (excessively high order)algebraicrelationships.

Similarproblemscanoccurdueto scaleeffects,wherefor exampletheinputof asystemmaybenumer-ically many ordersof magnitudelarger thantheresponse.Oneremedyis to scaledowntheinput beforefitting theresponseequation.Thiscanbeachievedby subtractingtheminimummeasuredinput from theinputvector, by dividing theinputvectorby its averageor by its maximumvalue,or by standardisingtheinput vectorby expressingeachelementin termsof thenumberof standarddeviationsabove or belowthemeanvalue(known as � scoresin statistics).Thelattertransformcanbeachievedin MATLAB with[p, S, mu] = polyfit(x, y, n) asoutlinedin thetext. For informationon theoutputvariableS consulttheonlinehelp.

Leastsquaresfitting is basedon inherentassumptions,oneof whichrequiresthatthedeviationsbetweenthealgebraicexpressionandthemeasuredresponse(theresiduals)berandomwith no discernablepat-tern. The text usesthis principle asa guideto limit ’overfitting’, as illustratedin Fig. 5.6-7of Palm.For thelinear, quadraticandexponentialregressionmodelstheresidualsclearlyshow a distinctpattern,while for thecubicregressionequationtheresidualsaremorehaphazard,althoughtheredoesseemto beanincreasein the(absolute)valueof theresidualsastheresponsegetslarger. In thisexampleregressionusingacubicequationproducesthemostrandompattern.

Self-Test 5.2

Palm: T5.6-1 (p.280)

69

Page 78: MATLAB Short Course

Module5. PlottingandModelBuilding

In many instancesin fitting it is often necessaryto force the regressionline or curve to passthroughafixedpoint on thepredictedresponseversusinput plot; invariably this point is theorigin. Thepracticeof insertinga leadingzero in eachof the input andmeasuredresponsevectorsbeforefitting doesnotachieve this goal; it maybring theregressionplot closerto theorigin but will not necessarilyforceit topassthroughtheorigin. In thesesituationsthepolyfit commandis not used.Someelementarycalculusprovidesthe solutionasexplainedin the text. For linear or transformedlinear systems,the regressionequationis of theform � �����M��� . In orderto forcethisregressionequationto passthroughtheoriginwerequiretheintercepton theordinateaxisto bezero,soit reducesto � ����� . Now SSEbetweenthe

regressionequationandthemeasuredresponsewill beataminimumwhen � (SSE)� � ��� ; i.e. when:

� (SSE)� � � �� ���� ����� � pred ��� � meas�  1¡

� �� ���� ���E¢ ��� � � � meas� £ ¡

� �� ���� ��� � � ¡ � ¡� �7¤ ��� � � meas� � � meas¡�  

� ��� �u��� ¤ ��� ¡� �7¤ � � � meas�  thisequalszerowhen

��� ��� ¤ ��� ¡� � ��� �u� ¤ � � � meas�� ��� ��� � ¡� � ��� �u� � � � meas�

�¥� �¦� �u� � � � meas��¦� �u� � ¡�which is thesameasEqn.5.6-6in thetext andastraightforwardsolution.

To forceaquadraticregressionthroughtheorigin thesamemethodof derivationappliesonly in thiscase

therearetwo variablesandhencetwo derivativesin theexpression§ (SSE)§ � ��� . Theregressionequation

is of theform � ��¨0� ¡ �O���J�7� which reducesto ����¨0� ¡ �7��� if it is to passthroughtheorigin.Settingeachpartialderivative to zeroproduces(asin Eqn.5.6-7and5.6-8of thetext):

¨ ��� �u� �:©� �O� ��� �u� �Eª� � ��� �u� � meas� � ¡�¨ ��� �u� �Eª� �O� ��� �u� � ¡� � ��� �u� � meas� � �

70

Page 79: MATLAB Short Course

5.3. FunctionDiscovery

whichconsistsof two simultaneousequationsin two unknownswhichcanbewrittenasamatrixexpres-sion: «

¬¬­ ®¯° ±�² ³:´° ®¯° ±�² ³Eµ°®¯° ±�² ³ µ° ®¯° ±�² ³E¶°· ¸¸¹�º«­5»¼ ·¹¾½

«¬¬­ ®¯° ±�² ¿ meas° ³ ¶°®¯° ±�² ¿ meas° ³ °

· ¸¸¹of theform À�Á ½� from which thesolutioncanbeobtainedusingtheMATLAB left division operatorÁ ½ ÀYà  .

Anotherproblemwith asimilarsolutionstrategy is thatof multiplelinear regressionwherethealgebraicexpressionhasthe form Ä ½ ¼ ² ³ ²MÅ ¼ ¶ ³ ¶ Å ¼ µ ³ µ Å�Æ Æ Æ!Å ¼ ® ³ ® Å�Ç where È is the numberofinput variables;in otherwordswheretheresponseof the(linearor transformedlinear)systemdependsonmorethanoneinputvariable.Thematrix representationfor a leastsquaressolutionfor three(3) inputvariableswith seven(7) measurements(for example)is:«

¬¬¬¬¬¬¬¬¬¬¬¬¬¬­

³ ² ² ³ ² ¶ ³ ² µbɳ ¶ ² ³ ¶ ¶ ³ ¶ µbɳ µ ² ³ µ ¶ ³ µ µbɳ ´ ² ³ ´ ¶ ³ ´ µbɳEÊ ² ³EÊ ¶ ³EÊ µbɳEË ² ³EË ¶ ³EË µbɳEÌ ² ³EÌ ¶ ³EÌ µbÉ

· ¸¸¸¸¸¸¸¸¸¸¸¸¸¸¹º«¬¬¬¬¬­¼ ²¼ ¶¼ µÇ· ¸¸¸¸¸¹ ½

«¬¬¬¬¬¬¬¬¬¬¬¬¬¬­

¿ meas²¿ meas¶¿ measµ¿ meas´¿ measÊ¿ measË¿ measÌ

· ¸¸¸¸¸¸¸¸¸¸¸¸¸¸¹which is alsoof theform À�Á ½� with thesolution Á ½ À�à  . As outlinedin thetext, thisparticularsetof matrix equationsis saidto beoverdeterminedbecausethenumberof simultaneousequationsusedtodescribeit (7) exceedsthenumberof unknown variables(4).

MATLAB providesa Fitting Interfacefor thepurposeof fitting regressioncurvesto data.This providesaquickvisualpictureaswell asnumericalindicatorsof thegoodnessof fit of theregressioncurve to thedata.Explorethe interfaceusingthetime-bacterialcountdatausedin Example5.6-2of thetext. Enterandplot thedatafirst:

clear;clc;t=[0:19];y=[6,13,23,33,54,83,118,156,210,282,350,440,557,685,815,990,1170,1350,1575,1830];plot(t,y,’o’);

FromtheFigure window, selectBasic Fitting from theTools menuthenclick theMore buttonto openthe right handpaneshown in Fig. 5.7-1of Palm. Checkthe Plot Residuals box andthenthe linearbox. Thedatapointsandfitted straightline aredisplayedin theupperpaneof theFigure window, the

71

Page 80: MATLAB Short Course

Module5. PlottingandModelBuilding

residualsin thelower paneandthecalculatedcoefficientsandnorm3 of residualsin theright handpaneof the Basic Fitting window. Next click the quadratic box anda plot of the leastsquaresquadraticregressioncurvewill besuperimposedon thelinearplot. Comparethetrendin theresidualsin thelowerpanewith thoseplottedin Fig. 5.6-7of thetext. Click thecubic, 4th degree, 5th degree etc.boxesinturnandnotethedecreasein thevalueof Í SSE. Theresultsmight look asfollows:

Polynomial Í SSE(ppm)

linear 892

quadratic 130

cubic 24.1

4thorder 23.6

5thorder 23.5

6thorder 21.4

Thedegreeof polynomialselectedin theoriginal examplewasthecubicbecausethis wasthesmallestorderwhichexhibitedamoreor lessrandompatternon theresidualversusresponseplot. It canbeseenfrom theabove thatthereis nosignificantimprovementin thenormof theresidualsfor regressionequa-tionshigherthanorder3, but quitedramaticimprovementsup to thatpoint. This reinforcesthenotionthat ’overfitting’ will not necessarilyproducea significantlymoreaccuratealgebraicrepresentationofthesystem.

5.4 3D Plotting and Graphics Output

Reading

Palm: Section5.8(pp.296-302)

Someof theseroutineshave beenintroducedpreviously. Theplot3 functiondraws a 3D line or scatterplot. Meshplots areproducedby first generatinga meshof Î , Ï coordinatepairs,applyingthe func-tional relationshipÐ�Ñ fn Ò ÎuÓ Ï:Ô to eachcoordinateandthenplotting the three-dimensionalmesh.TheMATLAB functionsmeshgrid andmesh areusedfor this purpose.Contourplotsalsousea generatedmesh.Thefunctionmeshc producesa meshplot superimposedover a contourplot. Thesurfc routineperformsa similar taskonly themeshis shadedin accordancewith the’height’ of the Ð data.

Hardand/orsoft copiesof MATLAB graphicscanbeproducedwith theprint command.For exampleahardcopy of a plot canbesentto anHP Deskjetprinterusingprint(’-ddjet500’);. A softcopy in JPEG4

and Windows bitmap graphicsformat can be generatedwith print(’-djpeg’,’myfile.jpg’); and print(’-dbmp16m’,’myfile.bmp’); respectively. Consulttheonlinehelpfor print for moredetail.

3Thenormof theresidualsis simply thesquarerootof thesumof squareserrors,i.e. norm= Õ SSE.4JPEGis anacronym for JointPhotographicExpertsGroup.

72

Page 81: MATLAB Short Course

SelfAssessmentQuestions

Self-Test 5.3

Palm: T5.8-1 (p.300)

SelfAssessmentQuestions

5.1 TheMATLAB commandsubplot(3,2,4) will:

(a) split thecurrentfigurewindow into eightpanesanddraw subsequentplots in thefirst paneof thesecondrow

(b) split thecurrentfigurewindow into six panesanddraw subsequentplots in thefirst paneofthefourth row

(c) plot thedatapoint correspondingto Ö�×�Ø!Ù Ú�×�Ø1Ù Û�×�Ü in thecurrentfigurewindow

(d) split thecurrentfigurewindow into six panesanddraw subsequentplots in thefirst paneofthesecondrow

(e) noneof theseanswers

5.2 TheMATLAB commandplot(y,x,’r:’) will plot:

(a) vectorx on theordinateaxisagainstvectory on theabscissawith a redsolid line

(b) vectory on theordinateaxisagainstvectorx on theabscissawith a redsolid line

(c) vectorx on theordinateaxisagainstvectory on theabscissawith a reddottedline

(d) vectory on theordinateaxisagainstvectorx on theabscissawith redsquaremarkers

(e) noneof theseanswers

5.3 Whichof thefollowing MATLAB routineswouldyouuseto form alineargraphof thethefunctionÚ5×�Ý ÖEÞ , whereÖ and Ú arevectorarraysof thesamesizeand Ý and ß arescalars:

(a) plot(x,log10(y))

(b) semilogx(x,log10(y))

(c) semilogy(log10(x),y)

(d) loglog(x,y)

(e) noneof theseanswers

73

Page 82: MATLAB Short Course

Module5. PlottingandModelBuilding

5.4 An exponentialfunctionof theform à�á�â1ã ä å formsastraightline on aplot of:

(a) logarithmof à againstlogarithmof æ(b) à againstlogarithmof æ(c) logarithmof à againstæ(d) à againstreciprocalof æ(e) noneof theseanswers

5.5 Themain objectives in leastsquaresfitting of algebraicrelationshipsto engineeringsystemsareto:

(a) incorporatethehighestorderof polynomialpossible

(b) maximisethesumof squareserrors

(c) minimise the sumof squareserrorswhile simultaneouslyensuringthat the errorsare ran-domlydistributed

(d) alwaysusea linearequation

(e) noneof theseanswers

5.6 In leastsquaresfitting of an algebraicrelationshipto an engineeringsystemtherearetwo errorcomponents.That componentwhich is explainedby the derived algebraicrelationshipis calledthe:

(a) sumof squareserrors

(b) residual

(c) sumof squaresregression

(d) coefficient of determination

(e) noneof theseanswers

5.7 In leastsquaresfitting of an algebraicrelationshipto an engineeringsystemthe coefficient ofdeterminationmaybedefinedas:

(a) sumof squaresregressiondividedby sumof squareserrors

(b) sumof squareserrorsdividedby sumof squarestotal

(c) oneminussumof squareserrorsdividedby sumof squaresregression

(d) theslopeof theline of bestfit to theregressioncurve

(e) noneof theseanswers

74

Page 83: MATLAB Short Course

TutorialProblems

5.8 In leastsquaresfitting of an algebraicrelationshipto an engineeringsystemthe coefficient ofdeterminationis usedas a dimensionlessmeasureof the goodnessof fit. A near-zero positivevaluefor this coefficient indicatesthatthederivedalgebraicrelationship:

(a) providesanear-perfectfit to theobservedresponse

(b) is a linearfunctionof theinput

(c) is apower functionof theinput

(d) providesavery poorfit to theobservedresponse

(e) noneof theseanswers

5.9 In leastsquaresfitting of an algebraicrelationshipto an engineeringsystemthe coefficient ofdeterminationis usedasa dimensionlessmeasureof thegoodnessof fit. A valueof unity for thiscoefficient indicates:

(a) SSR= SST

(b) SSR= SSE

(c) SSE= SST

(d) avery poorfit to theobservedresponse

(e) noneof theseanswers

5.10 In leastsquaresfitting of analgebraicrelationshipto anengineeringsystem,it is sometimesnec-essaryto forcethederivedalgebraicrelationshipto passthroughtheorigin of theplot of responseagainstinput. For quadraticrelationshipsthis involves solutionof the coefficients ç and è iné ê ç0ëEì�íHè�ë , whichcanbeachievedin MATLAB by:

(a) settingthefirst partialderivativesof ç and è to zeroandsolvingtheresultingtwo equationsin two unknownsusingtheleft division operator

(b) settingthe first partial derivativesof ç and è to zeroandsolving the resultingoverdeter-minedsetof linearequationsusingtheleft division operator

(c) insertingleadingzerosin the measuredinput andresponsevectorsbeforeusingthe polyfitfunctionto optimisethecoefficients

(d) settingSSEto zeroandsolvingfor ç and è by trial anderror

(e) noneof theseanswers

Tutorial Problems

5.1 PalmProblem5.5

5.2 PalmProblem5.6 [about54 days]

5.3 PalmProblem5.7î5.4 PalmProblem5.16î

Note: Producethesethreegraphsin a singlefigurewindow.

75

Page 84: MATLAB Short Course

Module5. PlottingandModelBuilding

5.5 PalmProblem5.24ïNote: Calculatethecoefficientof determinationin eachcase.

5.6 PalmProblem5.30ï5.7 PalmProblem5.32ï5.8 PalmProblem5.34ï5.9 PalmProblem5.43ï

5.10 PalmProblem5.49ïSelfAssessmentQuestions

Solutions

Table5.1: Solutionsto self assessmentquestions- Module5

Solution Comment

5.1 (d)

5.2 (c) thefirst argumentis alwaysplottedastheabscissa

5.3 (d) plot(log10(x),log10(y)) would achievethesameresult

5.4 (c) semilogarithmicin ð5.5 (c) leastsquaresfitting requiresthattheresidualsberandomlydistributed

5.6 (c)

5.7 (e) ñ òGó SSRSST

5.8 (d) an ñ ò valueof near-zerosuggestsno correlationat all betweenobservedandpredictedresponse

5.9 (a) indicatesthattheregressioncanexplainall of thedeviation from theline of bestfit

5.10 (a) anoverdeterminedsetof linearequationsis not possiblein thissituation

76

Page 85: MATLAB Short Course

Reference

Palm,W. J. (2001),Introductionto MATLAB6 for Engineers, McGraw-Hill.

77

Page 86: MATLAB Short Course

Reference

78

Page 87: MATLAB Short Course

Appendix A

Model Solutionsfor Self-Testsand TutorialProblems

A.1 The MATLAB Workspace

Problem 1.3

% P110.M% Samplesolution for Palm Problem 1.10clear;clc;% Set variablesR=0.08206;a=6.49;b=0.0562;n=1;V=22.41; 10

T=273.2;% Calculate and print ideal gas pressureP ideal=nô Rô T õ V% Calculate and print volume correction term of Van Der Waals equationterm1=nô R ô T õ (V ö nô b)% Calculate and print molecular attraction correction term of Van Der Waals equationterm2=ö aô nˆ 2 õ Vˆ 2% Add the last two terms to find Van Der Waals pressureP vdwaals=term1+term2% EOF 20

p110P ideal =

1.0004

79

Page 88: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

term1 =1.0029

term2 =÷ 0.0129P vdwaals =

0.9900diary off 10

The Van Der Waalspressureis ø ù ú ú ú û�ü7ú!ù ý ý ú úø ù ú ú ú ûÿþ ø ú ú�� ø ù ú û � lower thanthe ideal pressure.The

molecularvolumetermof theVanDer Waalspressureis ø ù ú ú � ýJü�ø ù ú ú ú ûø ù ú ú ú û þ ø ú ú���ú!ù � � � higherthan

theidealpressure.Themolecularattractiontermis� ø�ü ø ù ú ú ú û�ü7ú!ù ú!ø � ýø ù ú ú ú û��Oþ ø ú ú��ø ù � ý � lower than

theidealpressure.Hencethemolecularattractiontermaccountsfor mostof thedifferencebetweentheidealandtheVanDerWaalspressure.

Problem 1.5

% P114.M% Samplesolution for Palm Problem 1.14clear;clc;% Set coefficients of polynomialcoeffs=[13 182 ÷ 184 2503];% Find rootsmyroots=roots(coeffs)% Confirm roots by reconstructingpolynomialmypoly=poly(myroots) 10

% MATLAB returns coefficient of 1 for highest order term, so% multiply return coefficents by first elementof coefficient matrix% to reproduce original coefficentsfprintf('\n %.0f' ,mypoly. coeffs(1));fprintf('\n' );% EOF

p114myroots =÷ 15.6850

0.8425 + 3.4008i0.8425 ÷ 3.4008i

mypoly =1.0000 14.0000 ÷ 14.1538 192.5385

13182 10÷ 1842503

diary off

80

Page 89: MATLAB Short Course

A.1. TheMATLAB Workspace

Problem 1.6

x=[ � 15 � 8 9 8 5];y=[ � 20 12 � 4 8 9];z=(x � y)z =

0 1 0 0 1z=(x y)z =

1 0 1 0 0z=(x˜=y)z = 10

1 1 1 0 1z=(x==y)z =

0 0 0 1 0z=(y �� 4)z =

0 1 0 1 1diary off

(a) Thesecondandfifth elementsof � arelessthanthecorrespondingelementsof � .(b) Thefirst andthird elementsof � aregreaterthanthecorrespondingelementsof � .(c) Thefirst, second,third andfifth elementsof � arenotequalto thecorrespondingelementsof � .(d) Thefourthelementof � is equalto thecorrespondingelementof � .(e) Thesecond,fourthandfifth elementsof � aregreaterthan-4.

Problem 1.7

% P123.M% Samplesolution for Palm Problem 1.23clear;clc;% Evaluatepolynomial over range xlow to xhigh in incrementsof xincxlow= � 1;xhigh=1;xinc=0.001;x=[xlow:xinc:xhigh];% Set up coefficent matrix 10

coeffs=[3 � 5 � 28 � 5 200];% Evaluatepolynomial for each xy=polyval(coeffs,x);% Plot polynomialfigure('Position' ,get(0,'ScreenSize' ));plot(x,y,'r-' );xlabel('x' );ylabel('y' );title('Plot of y=3xˆ{4}-5xˆ{3}-28xˆ{2}-5x+200' );

81

Page 90: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

grid; 20

% Place cursor at peak on graph and use ginput to return coordinates of peak[xmax,ymax]=ginput(1)close;% Compare with numerical solution; peak occurs when dy� dx=0% Differentiate polynomial by hand to obtain coefficients of first derivativedydxcoeffs=[12 � 15 � 56 � 5];% Find real roots to the polynomial representingfirst derivative% in the range xlow to xhighdydxroots=roots(dydxcoeffs)xmax2=dydxroots(dydxroots� =xlow & dydxroots� =xhigh) 30

% Evaluateoriginal polynomial at xmax2ymax2=polyval(coeffs,xmax2)% EOF

p123xmax =� 0.0970ymax =

200.1568dydxroots=

2.9055� 1.5638� 0.0917xmax2 = 10� 0.0917ymax2 =

200.2271diary off

A.2 Array and Matrix Operations

Self-Test 2.1

B=[2 4 10 13;16 3 7 18;8 4 9 25;3 12 15 17]B =

2 4 10 1316 3 7 188 4 9 253 12 15 17

newB=[B;B']newB =

2 4 10 1316 3 7 18 10

8 4 9 253 12 15 172 16 8 34 3 4 12

82

Page 91: MATLAB Short Course

A.2. Array andMatrix Operations

10 7 9 1513 18 25 17

newB(5,3)ans =

8max(max(B)) 20

ans =25

[i j]=find(B==max(max(B)))i =

3j =

4min(min(B))ans =

2 30

[k l]=find(B==min(min(B)))k =

1l =

1C=sort(B)C =

2 3 7 133 4 9 178 4 10 18 40

16 12 15 25diary off

Self-Test 2.2

A=[21 27; � 18 8];B=[ � 7 � 3;9 4];A. � Bans =� 147 � 81� 162 32A. � Bans =� 3 � 9� 2 2 10

B.ˆ 3ans =� 343 � 27

729 64diary off

u=[6 � 8 3];w=[5 3 � 4];u� w'ans =

83

Page 92: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems� 6dot(u,w)ans =� 6A=[7 4; � 3 2;5 9];B=[1 8;7 6]; 10

A � Bans =

35 8011 � 1268 94

diary off

Self-Test 2.3

poly1=[20 � 7 5 10];poly2=[4 12 � 3];conv(poly1,poly2)ans =

80 212 � 124 121 105 � 30poly3=[12 5 � 2 3];poly4=[3 � 7 4];[quot remain]=deconv(poly3,poly4)quot =

4.0000 11.0000 10

remain =0 0.0000 59.0000 � 41.0000

poly5=[6 4 0 � 5];poly6=[12 � 7 3 9];polyval(poly5,2) � polyval(poly6,2)ans =

0.7108diary off

Problem 2.1

x=0:2:10x =

0 2 4 6 8 10A(1,1:length(x))=3 � xA =

0 6 12 18 24 30A(2,1:length(x))=5 � x � 20A =

0 6 12 18 24 30� 20 � 10 0 10 20 30 10

diary off

84

Page 93: MATLAB Short Course

A.2. Array andMatrix Operations

Problem 2.2

A=[3 7 � 4 12; � 5 9 10 2;6 13 8 11;15 5 4 1]A =

3 7 � 4 12� 5 9 10 26 13 8 11

15 5 4 1v=A(:,2)v =

79 10

135

w=A(2,:)w = � 5 9 10 2diary off

Problem 2.4

F=[400 550 700 500 600]F =

400 550 700 500 600d=[2 0.5 0.75 1.5 3]d =

2.0000 0.5000 0.7500 1.5000 3.0000F. � dans =

800 275 525 750 1800sum(F. � d) 10

ans =4150

diary off

Problem 2.5

wage=[5 5.5 6.5 6 6.25]wage =

5.0000 5.5000 6.5000 6.0000 6.2500hours=[40 43 37 50 45]hours =

40 43 37 50 45output=[1000 1100 1000 1200 1100]output =

1000 1100 1000 1200 1100earnings=wage. � hours 10

earnings=

85

Page 94: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

200.0000 236.5000 240.5000 300.0000 281.2500total salary=sum(earnings)total salary =

1.2583e+003num widgets=sum(output)num widgets =

5400costperwidget=total salary� num widgetscostperwidget= 20

0.2330hoursperwidget=sum(hours) � num widgetshoursperwidget=

0.0398outputperhour=output. � hoursoutputperhour=

25.0000 25.5814 27.0270 24.0000 24.4444mosteffic=find(outputperhour==max(outputperhour))mosteffic =

3 30

leasteffic=find(outputperhour==min(outputperhour))leasteffic =

4diary off

Problem 2.6

First calculate� in termsof � (total area)and :

�"!$# %�'&)( %*## %�+!$�-, ( *#�+! �-,.( *## ! �# ,/( 0 (A.1)

% area given as 1600sq.ft.A=1600;% fill radius vector in incrementsof 0.01ft; max say 100ftR=0.01:0.01:100;% calculate L for each R from given AL=A. � (2. 1 R)2 pi. 1 R.� 4;% calculate fence lengths for each R and Llengthstraight=2. 1 (L+R);lengthcurve=pi.1 R;% find total cost 10

totalcost=lengthstraight.1 30+lengthcurve.1 40;% optimum R is sameindex which producesminimum costRoptimum=R(find(totalcost==min(totalcost)));% sameindex for L

86

Page 95: MATLAB Short Course

A.2. Array andMatrix Operations

Loptimum=L(find(R==Roptimum));% print resultsfprintf('Optimum value of R is %.2f feet.\n' ,Roptimum);Optimum value of R is 18.61 feet.fprintf('Optimum value of L is %.2f feet.\n' ,Loptimum);Optimum value of L is 28.37 feet. 20

fprintf('Minimum cost of fence is $%.2f.\n' ,min(totalcost));Minimum cost of fence is $5157.48.diary off

Now confirmresultanalytically. Thetotal cost( 3 ) canbeexpressedas:3"465 798 : ;=<�: >?@<�A 7 B@>subst.for ; from Eqn.(A.1): 3"465 7DCE:DCGF: >IH BJ>A.K <L: > K <=AE7 BJ>465 7DC�F>IH B@>: <L: > K <=AE7 BJ>4 5 7 F>+HNM O B@>-<�P 7 >-<=AE7 BJ>4 5 7 F> <L: O B@>-<�P 7 >

Now 3 will beataminimumwith respectto > when Q 3Q > 4-7 :Q 3Q > 4RQQ > C 5 7 F> <�: O BJ>N<LP 7 > K4SH 5 7 F>%T <�: O BU<LP 7thisequalszerowhen: : O BU<LP 7V4 5 7 F> T> T 8 : O BW<�P 7 ?X465 7 F>Y4YZ 5 7 F: O BU<LP 74YZ 5 7�[ M P 7 7: O BU<LP 74 M \^] P M feet

sothatfrom Eqn.(A.1): ;+4 F:D[ M \^] P M H B=[ M \E] P MA46: \^] 5 P feet

from which thetotal costis: 3"4 5 7 F> <L: O B@>-<�P 7 >4 5 7�[ M P 7 7M \^] P M <�: O B=[ M \^] P M <LP 7�[ M \^] P M4 $O^M OE_ (Q.E.D.)

87

Page 96: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

Problem 2.7

% RESS.MTutorial problem 2.22 of Palmclear;clc;% Source resistancevectorRs=[10 15 20 25];% Load resistancevectorRl=[10 15 20 25 30];% print headersfprintf(' Source Optimum\nResistance(ohms) Load Resistance(ohms)\n' );% Find maximumvalue of r for each Rs 10

for i=1:length(Rs)r(i,:)=Rl. ` (Rs(i)+Rl). 2;Rlopt(i)=Rl(find(r(i,:)==max(r(i,:))));% print resultsfprintf('%8.0f %16.0f\n' ,Rs(i),Rlopt(i));

end% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

ressSource Optimum

Resistance(ohms) Load Resistance(ohms)10 1015 1520 2025 25

diary off

Notethatit is notnecessaryto usethefor loopfor thisproblemasthequestionasksfor aresultonly for aspecificvalueof a%b , notfor all valuesof a%b . It canbeconfirmedanalytically(usingelementarycalculusasin theprevioussolution)thatthemaximumpower transferfor this systemoccurswhen acbUd-a%e .Problem 2.8

% DRAG1.M Palm tutorial problem 2.25clear;clc;% fill attack angle vectoralpha=f 2:0.2:22;CLcoeff=[4.47e f 5 1.15e f 3 6.66e f 2 1.02e f 1];CDcoeff=[5.75e f 6 5.09e f 4 1.81e f 4 1.25e f 2];% evaluate CL and CD for each alphaCL=polyval(CLcoeff,alpha);CD=polyval(CDcoeff,alpha); 10

% find lift to drag ratio

88

Page 97: MATLAB Short Course

A.2. Array andMatrix Operations

liftondrag=CL.g CD;% find alpha which producesmax lift to drag ratioalphamax=alpha(find(liftondrag==max(liftondrag)));% set plot titlemytitle=sprintf('Lift to Drag Ratio for Airfoil for Various Angles of Attack' );% plot lift to drag ratio against alphafigure('Position' ,get(0,'ScreenSize' ));plot(alpha,liftondrag,'r-' );xlabel('Angle of attack {\alpha} (degrees)' ); 20

ylabel('Lift to drag ratio (L/D)' );title(mytitle);% set axis limitsaxis([min(alpha)max(alpha)0 max(liftondrag)h 1.1]);% include dashedlines and text to show optimum alpha and maximumL g Dline([alphamaxalphamax],[min(liftondrag)max(liftondrag)],'LineStyle' ,'-.' );line([min(alpha)alphamax],[max(liftondrag)max(liftondrag)],'LineStyle' ,'-.' );text(alphamax,1,num2str(alphamax),'HorizontalAlignment' ,'right' ,.. .

'VerticalAlignment' ,'bottom' ,'Rotatio n' ,90);text(1,max(liftondrag),num2str(max(liftondrag)),'HorizontalAlignment' ,'center' ,.. . 30

'VerticalAlignment' ,'bottom' );grid;pause;% Plot to PostScript fileorient landscape;print('-deps' ,'drag1.eps' );close;% EOF

ThePostScriptgraphicfile DRAG1.EPS is reproducedin FigureA.1.

Problem 2.9

t=0:0.5:5;yvec=10. h t+3;P=zeros(length(t),3);P(:,1)=2;P(:,2)=yvec';disp(P)

2 3 02 8 02 13 02 18 0 10

2 23 02 28 02 33 02 38 02 43 02 48 02 53 0

d5=P(find(t==5),:)d5 =

89

Page 98: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

0 5 10 15 200

2

4

6

8

10

12

14

16

18

Angle of attack α (degrees)

Lift

to d

rag

ratio

(L/

D)

Lift to Drag Ratio for Airfoil for Various Angles of Attack

3.8

17.9415

FigureA.1: Lift to dragratio for airfoil

2 53 0 20

mass=5;v=[0 10 0];L=mass. i (cross(d5,v))L =

0 0 100diary off

Problem 2.10

% position vector to line of action of forcer=[2 4 0];% convert degrees to radiansalpha=40 j 360 i 2 i pi;% direction cosinesfor forcedircosF=[cos(alpha)k sin(alpha)0];% force magnitude times direction cosinesgives force vectorF=dircosF.i 600;% cross product of position and force vector gives momentabout origincross(r,F) 10

90

Page 99: MATLAB Short Course

A.2. Array andMatrix Operations

ans =1.0e+003 l

0 0 m 2.6099diary off

Problem 2.11

% find direction cosinesfor forcen=[3 4 5];magn=sqrt(sum(n.ˆ 2));dircosn=n.n magndircosn =

0.4243 0.5657 0.7071% find force vector by multiplying force magnitude by direction cosinesF=100. l dircosn;% now find direction cosinesfor line onto which to project forcer=[6 6 2]; 10

magr=sqrt(sum(r.ˆ 2));dircosr=r.n magrdircosr =

0.6882 0.6882 0.2294% dot product is projection of force onto linedot(F,dircosr)ans =

84.3551diary off

Problem 2.12

% force FF=[10 m 5 4];% find direction cosinesfor FmagF=sqrt(sum(F.ˆ 2));dircosF=F.n magF;% position vector rr=[ m 3 7 2];% find direction cosinesfor rmagr=sqrt(sum(r.ˆ 2));dircosr=r.n magr; 10

% position vector nn=[6 8 m 7];% find direction cosinesfor nmagn=sqrt(sum(n.ˆ 2));dircosn=n.n magn;% find scalar triple productM=dot(cross(r,F),n)M =

869diary off 20

91

Page 100: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

Problem 2.13

A=[10 o 9 o 6 12]A =

10 o 9 o 6 12B=[5 o 4 o 12 8]B =

5 o 4 o 12 8conv(A,B)ans =

50 o 85 o 114 272 o 48 o 192 96diary off 10

A.3 Files,Functions and Data Structures

Self-Test 3.1

% RAD2DEG.M% Displays a table converting radians to degrees% Self-test3.3-1 of Palm.clear;clc;rads=[1:5];myfactor=360 p (2 q pi);degs=rads.q myfactor;mytable=[rads;degs];fprintf('Radians Degrees' ); 10

fprintf('\n%5.1f %10.1f' ,mytable);%EOF

rad2degRadians Degrees

1.0 57.32.0 114.63.0 171.94.0 229.25.0 286.5

diary off

% SPHERE.M% Determinesvolume of sphere for given radius% Self-test3.3-2 of Palm%clear;

92

Page 101: MATLAB Short Course

A.3. Files,FunctionsandDataStructures

clc;radius=1:0.1:2;vol=4 r pi s 3. r radius. 3;thistable(:,1)=radius';thistable(:,2)=vol'; 10

disp('Radius (m) Volume (cu.m)' );disp(thistable);%EOF

sphereRadius (m) Volume (cu.m)

1.0000 4.18881.1000 5.57531.2000 7.23821.3000 9.20281.4000 11.49401.5000 14.13721.6000 17.15731.7000 20.5795 10

1.8000 24.42901.9000 28.73092.0000 33.5103

diary off

% SAREA.M% Calculatessurface area of a sphere% Self-test3.3-3 of Palmclear;clc;radius=input('Enter radius of sphere (m) :' );fprintf('\nThe surface area of a sphere of radius %.3f m is %.3f sq.m.' ,. . .

radius,4 r pi r radius 2);%EOF

sareaEnter radius of sphere(m) :0.5

The surface area of a sphereof radius 0.500 m is 3.142 sq.m.diary off

Self-Test 3.2

x=1:5;y=12:2:20;logprod=log10(x. r y)logprod =

1.0792 1.4472 1.6812 1.8573 2.0000sumlog=log10(x)+log10(y)sumlog =

93

Page 102: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

1.0792 1.4472 1.6812 1.8573 2.0000diary off

x=sqrt(2+6i)x =

2.0402 + 1.4705iabs(x)ans =

2.5149angle(x)ans =

0.6245real(x) 10

ans =2.0402

imag(x)ans =

1.4705diary off

x=1:5;cos(x)+i t sin(x)ans =

Columns 1 through 40.5403 + 0.8415i u 0.4161 + 0.9093i u 0.9900 + 0.1411i u 0.6536 u 0.7568i

Column 50.2837 u 0.9589i

exp(i t x)ans =

Columns 1 through 4 10

0.5403 + 0.8415i u 0.4161 + 0.9093i u 0.9900 + 0.1411i u 0.6536 u 0.7568iColumn 50.2837 u 0.9589i

diary off

x=0:pi v 8:2 t pi;functionx=asin(x)+acos(x)functionx =

Columns 1 through 71.5708 1.5708 1.5708 1.5708 1.5708 1.5708 1.5708

Columns 8 through 141.5708 1.5708 1.5708 1.5708 1.5708 1.5708 1.5708

Columns 15 through 171.5708 1.5708 1.5708

find(functionx==pi v 2) 10

ans =Columns 1 through 13

1 2 3 4 5 6 7 8 9 10 11 12 13Columns 14 through 17

14 15 16 17diary off

94

Page 103: MATLAB Short Course

A.3. Files,FunctionsandDataStructures

x=0:pi w 256:pi w 8;% note that tan(x) is undefinedfor x=pi w 2functionx1=2. x tan(x).w (1 y tan(x). 2);functionx2=tan(2. x x);mytable(:,1)=functionx1';mytable(:,2)=functionx2';disp(mytable)

0 00.0245 0.02450.0491 0.0491 10

0.0738 0.07380.0985 0.09850.1233 0.12330.1483 0.14830.1735 0.17350.1989 0.19890.2246 0.22460.2505 0.25050.2767 0.27670.3033 0.3033 20

0.3304 0.33040.3578 0.35780.3857 0.38570.4142 0.41420.4433 0.44330.4730 0.47300.5034 0.50340.5345 0.53450.5665 0.56650.5994 0.5994 30

0.6332 0.63320.6682 0.66820.7043 0.70430.7417 0.74170.7804 0.78040.8207 0.82070.8626 0.86260.9063 0.90630.9521 0.95211.0000 1.0000 40

diary off

x=0:0.2:5;functionx1=sin(i. x x);functionx2=i. x sinh(x);find(functionx1==functionx2)ans =

Columns 1 through 131 2 3 4 5 6 7 8 9 10 11 12 13

Columns 14 through 2614 15 16 17 18 19 20 21 22 23 24 25 26

find(functionx1=functionx2) 10

95

Page 104: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

ans =[ ]

diary off

Self-Test 3.3

function f=myfunct1(x)% User definedfunction for self-test3.5-1 of Palmf=exp(z 0.2. { x). { sin(x+2) z 0.1;%EOF

% plot function firstx=0:0.1:10;plot(x,myfunct1(x));% myfunct1is zero at approx. x=1, 4.5 and 7fzero('myfunct1' ,1)ans =

1.0187fzero('myfunct1' ,4.5)ans =

4.5334 10

fzero('myfunct1' ,7)ans =

7.0066% confirm roots of myfunct1myfunct1(fzero('myfunct1' ,1))ans =

2.7756e z 017myfunct1(fzero('myfunct1' ,4.5))ans =

1.5266e z 016 20

myfunct1(fzero('myfunct1' ,7))ans =z 2.7756e z 016% each of which is close enoughto zerodiary off

function f=myfunct2(x)% User definedfunction for self-test3.5-2 of Palmf=1+exp(z 0.2. { x). { sin(x+2);%EOF

x=0:0.1:10;% plot function firstplot(x,myfunct2(x));% minimum functional valuesoccur at approx. x=2.5 and x=8.5fminbnd('myfunct2' ,0,3)ans =

2.5150

96

Page 105: MATLAB Short Course

A.3. Files,FunctionsandDataStructures

fminbnd('myfunct2' ,3,10)ans =

8.7982 10

% now find functional values at thesepointsmyfunct2(fminbnd('myfunct2' ,0,3))ans =

0.4070myfunct2(fminbnd('myfunct2' ,3,10))ans =

0.8312% minimum functional value of y=0.407 occurs at x=2.515diary off

Self-Test 3.4|is acell comprisingonerow andfour columns.A } 1:2 ~ is thecontentsof thefirst andsecondcolumns

of the first row of the cell, in this case � � � �E� �^� � � and � �E� �^� � � . [A2; A4] is a 3× 2 matrix the first rowof which containsthe contentsof the secondcolumn(of the first row) of

|(a 1× 3 vector),with the

secondrow holdingthecontentsof fourth column(alsoa 1× 3 vector).Thesemi-coloncombinestheseinto a2× 3 matrix. Thecommandmin(A } 2:3 ~ ) producesanerrormessagebecausethesecondandthirdcolumnsof cell

|hold vectorsof differentsize.To determinetheminimumvalueof all elementsin the

secondandthird columnsof|

, thecommandmin([min(A } 2 ~ ) min(A } 3 ~ )]) couldbeused.

Problem 3.1

% FUNCTX1.M main script for Problem 3.13 of Palmclear;clc;x=input('Enter x array. . .' );tabx1(x);% EOF

function tabx1(x)% TABX1.M tabulates given x and calculated z values% Prob 3.13 of Palmy=cos(x);z=y. 3 � 3 � y.ˆ 2+4 � y+10;mytable(:,1)=x';mytable(:,2)=z';disp(' x z' );disp(mytable);% EOF 10

Theoutputfrom theMATLAB commandwindow is asfollows:

functx1

97

Page 106: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

Enter x array. . .[0:0.1:1]x z

0 12.00000.1000 11.99500.2000 11.98010.3000 11.95520.4000 11.92060.5000 11.87570.6000 11.8200 10

0.7000 11.75180.8000 11.66880.9000 11.56741.0000 11.4432

diary off

Problem 3.2

% BELTF1.M script for solution of Problem 3.15 of Palmclear;clc;[f2, beta, mu]=getit;fprintf('\nBelt force F1 is %.1f N\n.' ,beltf(f2,beta,mu));% EOF

function [f2, beta, mu]=getit;% GETIT.M prompts user to input force f2, angle beta and fric coeff mu% Problem 3.15 of Palmf2=input('Enter belt force f2 (Newtons). . .' );beta=input('Enter belt angle beta (degrees). . .' );mu=input('Enter friction coefficient mu. . .' );% convert degrees to radiansbeta=beta� 360 � 2 � pi;% EOF

function f1=beltf(f2,beta,mu)% BELTF.M calculatesbelt force around a cylinder% f2 is in Newtons and beta is in radians% Problem 3.15 of Palmf1=f2.� exp(mu.� beta);%EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

beltf1Enter belt force f2 (Newtons). . .100Enter belt angle beta (degrees). . .130Enter friction coefficient mu. . .0.3

98

Page 107: MATLAB Short Course

A.3. Files,FunctionsandDataStructures

Belt force F1 is 197.5 N.diary off

Problem 3.3

% TIMEHT.M script to calculate height-timerelationship for Problem 3.18 of Palmclear;clc;% read data[ht,vel,acc]=read1;% calculate timethistime=httime(ht,vel,acc);% print resultif(length(thistime)� 1)

% two solutions (one on way up, one on way down) 10

fprintf('\nTime to height of %.1fm is %.2fs and %.2fs.\n' ,ht,thistime(1),thistime(2));else

% one solution (time to maximumheight)fprintf('\nTime to height of %.1fm is %.2fs.\n' ,ht,thistime);

end

function [h,v0,g]=read1;% READ1.M reads input for Problem 3.18 of Palmh=input('Enter height (m). . .' );v0=input('Enter initial velocity (m/s). . .' );g=input('Enter gravitational acceleration (m/sˆ2). . .' );% EOF

function risetime=httime(h,v0,g)% HTTIME.M calculatestime to rise to height h from initial% velocity v0 under negative acceleration g% Problem 3.18 of Palm%% requires solution of quadratic 0.5� g� tˆ 2 - v0� t + h = 0risetime=roots([0.5 � g, � v0, h]);% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

timehtEnter height (m). . .100Enter initial velocity (m� s). . .50Enter gravitational acceleration(m� s 2). . .9.81

Time to height of 100.0m is 7.46s and 2.73s.diary off

99

Page 108: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

Problem 3.4

% TANK.M optimisescost of water storage tank% Problem 3.19 of Palm%clear;clc;% fill radius vector over somereasonablerange% say 1 - 10m in incrementsof 0.01mradius=1:0.01:10;% find radius which minimisescost of tank using fminbnd function[minradius, mincost]=fminbnd('costfn' ,min(radius),max(radius)); 10

% print resultsfprintf('\n Tank radius for minimum cost is %.2f m.' ,minradius);fprintf('\n Tank height required is %.2f m.' ,tankht(minradius));fprintf('\n Minimum cost of tank is $%.0f.\n' ,mincost);% EOF

function thiscost=costfn(radius)% COSTFN.Mcalculatescost function for tank of given radius% Problem 3.19 of Palm%% calculate height for given radiush=tankht(radius);% cost functionsidecost=300;topcost=400;thiscost=topcost� 2 � pi. � radius. 2+sidecost� 2 � pi. � radius.� h; 10

% EOF

function ht=tankht(radius)% TANKHT.M calculatesheight of water tank for given radius and volume% Problem 3.19 of Palm%volume=500;ht=volume.� (pi. � radius. 2) � 2. � radius.� 3;% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

tank

Tank radius for minimum cost is 4.92 m.Tank height required is 3.28 m.Minimum cost of tank is $91394.diary off

100

Page 109: MATLAB Short Course

A.3. Files,FunctionsandDataStructures

Now checkresultby handcalculation:

given �@� � �D�)� �@� ����6� � �then ��� � � ��9� �D  � ��

andsince ¡"�$¢ � ��£ � �@� � � � � ��£ � �@� �then ¡"�6¤ � � �@� �¥�L¦ � � �@��§ � � ��@� �  � ��D¨�6¤ � � �@� �¥� � � � � � ��   ¢ � � �@� ��$¢ � � �@� �¥� � � � � � ��

where¡ is total cost.Now C will beataminimumwith respectto � when © ¡© � �-� :© ¡© � �6¤ � � �9�  � � � � � �� � �-�

when ¤ � � �9�V� � � � � � �� �� � � � � � � � �¤ � � ��ª�$¢9« ¬ � ¢ m

from which �­� � � ��=£U¢9« ¬ � ¢ �D  � £U¢9« ¬ � ¢�®� � « � ¤ � m

Problem 3.5

Sincethe fzero function acceptsonly one variable, it is necessaryto declarer as a global variable.Furthermorethefzero functiondeterminesthevalueof ¯ wheretheplot of ° against crossesthe °��-�axis. To usethis function to find whereit crossesthe °.�²± axis ( ± beinga positive constant),thefunctionmustbemodifiedto effectively shift the °'�)� axisup by anamount± . This canbeachievedby including the x variable(percentagecapacityremaining)in the function, whereit too mustalsobedeclaredglobal.

% DOWNTIME.M script to determinedrawdown time for reservoir% Palm Problem 3.22clear;clc;global x r;x=input('Enter x (%). . .' );r=input('Enter r (l/day). . .' );fprintf('\nTime to drawdown to %.1f%% capacity at usage of %.2e l/day is %.2f days.\n' ,. . .

x,r,findtime(x,r));% EOF 10

101

Page 110: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

function tt=findtime(x,r);% FINDTIME.M finds time for reservoir to drawdown to% x percent of capacity for daily draft r% Palm Problem 3.22% use trial value of t=10 daystt=fzero('resvol' ,10);% EOF

function v=resvol(t);% RESVOL.M volume in reservoir as a function of time,% draft rate and percentage reduction required% Problem 3.22 of Palmglobal x r;v0=1e9;v=v0+1e8 ³ (1 ´ exp( t. µ 100)) ´ r ³ t ´ x µ 100 ³ v0;% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

downtimeEnter x (%).. .50Enter r (l µ day).. .1e7

Time to drawdown to 50.0% capacity at usage of 1.00e+007l µ day is 54.18 days.diary off

Problem 3.6

Therequiredcartonvolumeis declaredaglobalvariablesothattheheightcanbecalculatedfrom withinthesurfaceareafunction.

% CARTON.M script to determineoptimum dimensionsof% open rectangular carton% for ENG3103clear;clc;global vol;vol=input('Enter required carton volume (litres). . .' );fprintf('\nOptimum dimensions for a volume of %.2f litres are:' ,vol);% convert to cubic millimetresvol=vol ³ 1e6; 10

% find width and depth for minimum surface area at given volumedimen=fminsearch('surfarea' ,[10 10]);fprintf('\nwidth: %.0f mm\ndepth: %.0f mm\nheight: %.0f mm\n' ,. . .

dimen(1),dimen(2),getht(dimen));% EOF

102

Page 111: MATLAB Short Course

A.3. Files,FunctionsandDataStructures

function sa=surfarea(x)% SURFAREA.M function to calculate surfacearea of an% open rectangular box% x(1) is width, x(2) is depthheight=getht(x);sa=x(1) ¶ x(2)+2 ¶ x(1) ¶ height+2 ¶ x(2) ¶ height;% EOF

function ht=getht(dimen)% GETHT.M function to calculate carton height from known width,% depth and volumeglobal vol;ht=vol · (dimen(1) ¶ dimen(2));% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

cartonEnter required carton volume (litres). . .1.0

Optimum dimensionsfor a volume of 1.00 litres are:width: 126 mmdepth: 126 mmheight: 63 mmdiary off

Somepartialdifferentialcalculuswill confirmthesolution. Let width, depthandheightof cartonbe ¸ ,¹ and º respectively. Thesurfaceareais givenby »-¼)¸ ¹D½N¾ ¸@º ½N¾ ¹ º andthevolumeby ¿L¼)¸ ¹ º .SubstitutingºD¼ ¿¸ ¹ andsettingfirst partialderivativesequalto zero:

»À¼$¸ ¹½�¾ ¸ ¿¸ ¹ ½�¾ ¹ ¿¸ ¹ ¼N¸ ¹½ ¾ ¿¹ ½ ¾ ¿¸so Á »Á ¸ ¼ ¹D ¾ ¿¸@à ¼-Ä when ¹ ¼ ¾ ¿¸@Ã

and Á »Á ¹ ¼$¸  ¾ ¿¹ à ¼NÄ when ¸W¼ ¾ ¿¹ Ãi.e. ¹ ¼ ¾ ¿¸ à and ¸G¼ ¾ ¿¹ à at theoptimumpoint. Solvingsimultaneouslywith ¿G¼/Å Ä Æ mmÇ :

¹ ¼ ¾ ¿¸@à ¼ ¾ ¿ ¹EÈÉ ¿Jà ¼ ¹EȾ ¿so¹ Ǿ ¿ ¼YÅ and ¹ ¼)Ê ¾ ¿ÌË ÍÎ ¼ÐÏ ¾�Ñ Å Ä Æ Ò ÍÎ ¼/Å ¾ Ó mm

from which ¸G¼/Å ¾ Ó mmand ºD¼ Ó Ô mm.

103

Page 112: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

Problem 3.7

% CELLTEST.M assigningcell arrays% Problem 3.23 Palmclear;clc;% cell indexingmycell1=Õ 'Motor 28C' ,'Test ID6' ;[3,9;7,2],[6,5,1] Ö ;% content indexing - cannot assign more than one cell elementat one timemycell2Õ 1,1 Ö ='Motor 28C' ;mycell2Õ 1,2 Ö ='Test ID6' ;mycell2Õ 2,1 Ö =[3,9;7,2]; 10

mycell2Õ 2,2 Ö =[6,5,1];% display cell contentscelldisp(mycell1);celldisp(mycell2);% find (1,1)elementof (2,1) cell% theseshould be the sameirrespectiveof methodof assignmentmycell1Õ 2,1 Ö (1,1)mycell2Õ 2,1 Ö (1,1)% EOF

20

Theoutputfrom theMATLAB commandwindow is asfollows:

celltestmycell1Õ 1,1 Ö =Motor 28Cmycell1Õ 2,1 Ö =

3 97 2

mycell1Õ 1,2 Ö =Test ID6mycell1Õ 2,2 Ö =

6 5 1 10

mycell2Õ 1,1 Ö =Motor 28Cmycell2Õ 2,1 Ö =

3 97 2

mycell2Õ 1,2 Ö =Test ID6mycell2Õ 2,2 Ö =

6 5 1ans = 20

3ans =

3diary off

104

Page 113: MATLAB Short Course

A.3. Files,FunctionsandDataStructures

Problem 3.8

Layoutdesignfor variouscombinationsof × , Ø and Ù :×EÚ ØÛÚ Ù Ú × Ü ØÛÚ Ù Ú × Ý ØÛÚ Ù Ú × Þ ØÛÚ Ù Ú×EÚ ØÛÚ Ù Ü × Ü ØÛÚ Ù Ü × Ý ØÛÚ Ù Ü × Þ ØÛÚ Ù Ü×EÚ ØÛÚ Ù Ý × Ü ØÛÚ Ù Ý × Ý ØÛÚ Ù Ý × Þ ØÛÚ Ù Ý×EÚ Ø¥Ü Ù Ú × Ü Ø¥Ü Ù Ú × Ý Ø¥Ü Ù Ú × Þ Ø¥Ü Ù Ú×EÚ Ø¥Ü Ù Ü × Ü Ø¥Ü Ù Ü × Ý Ø¥Ü Ù Ü × Þ Ø¥Ü Ù Ü×EÚ Ø¥Ü Ù Ý × Ü Ø¥Ü Ù Ý × Ý Ø¥Ü Ù Ý × Þ Ø¥Ü Ù Ý×EÚ Ø¥Ý Ù Ú × Ü Ø¥Ý Ù Ú × Ý Ø¥Ý Ù Ú × Þ Ø¥Ý Ù Ú×EÚ Ø¥Ý Ù Ü × Ü Ø¥Ý Ù Ü × Ý Ø¥Ý Ù Ü × Þ Ø¥Ý Ù Ü×EÚ Ø¥Ý Ù Ý × Ü Ø¥Ý Ù Ý × Ý Ø¥Ý Ù Ý × Þ Ø¥Ý Ù Ý

% CAPAC.M capacitancetable% for Palm Problem 3.24clear;clc;% fill distance, length and radius vectorsd=[0.003, 0.004, 0.005, 0.01];L=[1, 2, 3];r=[0.001, 0.002, 0.003];% fill cell arrays according to predefinedscheme:% each column of outer cell array has constantdistance(four required) 10

% each row of outer cell array has constantlength (three required)% variable radii in third column of inner cell arrays (three rows required)% calculated capacitancein fourth column of inner cell arrays% Note this would be much simpler to do in a loopmycapac(1,1)= ß ß d(1),L(1),r(1),thiscap(d(1),L(1),r(1));.. .

d(1),L(1),r(2),thiscap(d(1),L(1),r(2));.. .d(1),L(1),r(3),thiscap(d(1),L(1),r(3)) à à ;

mycapac(1,2)= ß ß d(2),L(1),r(1),thiscap(d(2),L(1),r(1));.. .d(2),L(1),r(2),thiscap(d(2),L(1),r(2));.. .d(2),L(1),r(3),thiscap(d(2),L(1),r(3)) à à ; 20

mycapac(1,3)= ß ß d(3),L(1),r(1),thiscap(d(3),L(1),r(1));.. .d(3),L(1),r(2),thiscap(d(3),L(1),r(2));.. .d(3),L(1),r(3),thiscap(d(3),L(1),r(3)) à à ;

mycapac(1,4)= ß ß d(4),L(1),r(1),thiscap(d(4),L(1),r(1));.. .d(4),L(1),r(2),thiscap(d(4),L(1),r(2));.. .d(4),L(1),r(3),thiscap(d(4),L(1),r(3)) à à ;

mycapac(2,1)= ß ß d(1),L(2),r(1),thiscap(d(1),L(2),r(1));.. .d(1),L(2),r(2),thiscap(d(1),L(2),r(2));.. .d(1),L(2),r(3),thiscap(d(1),L(2),r(3)) à à ;

mycapac(2,2)= ß ß d(2),L(2),r(1),thiscap(d(2),L(2),r(1));.. . 30

d(2),L(2),r(2),thiscap(d(2),L(2),r(2));.. .d(2),L(2),r(3),thiscap(d(2),L(2),r(3)) à à ;

mycapac(2,3)= ß ß d(3),L(2),r(1),thiscap(d(3),L(2),r(1));.. .d(3),L(2),r(2),thiscap(d(3),L(2),r(2));.. .d(3),L(2),r(3),thiscap(d(3),L(2),r(3)) à à ;

105

Page 114: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

mycapac(2,4)= á á d(4),L(2),r(1),thiscap(d(4),L(2),r(1));.. .d(4),L(2),r(2),thiscap(d(4),L(2),r(2));.. .d(4),L(2),r(3),thiscap(d(4),L(2),r(3)) â â ;

mycapac(3,1)= á á d(1),L(3),r(1),thiscap(d(1),L(3),r(1));.. .d(1),L(3),r(2),thiscap(d(1),L(3),r(2));.. . 40

d(1),L(3),r(3),thiscap(d(1),L(3),r(3)) â â ;mycapac(3,2)= á á d(2),L(3),r(1),thiscap(d(2),L(3),r(1));.. .

d(2),L(3),r(2),thiscap(d(2),L(3),r(2));.. .d(2),L(3),r(3),thiscap(d(2),L(3),r(3)) â â ;

mycapac(3,3)= á á d(3),L(3),r(1),thiscap(d(3),L(3),r(1));.. .d(3),L(3),r(2),thiscap(d(3),L(3),r(2));.. .d(3),L(3),r(3),thiscap(d(3),L(3),r(3)) â â ;

mycapac(3,4)= á á d(4),L(3),r(1),thiscap(d(4),L(3),r(1));.. .d(4),L(3),r(2),thiscap(d(4),L(3),r(2));.. .d(4),L(3),r(3),thiscap(d(4),L(3),r(3)) â â ; 50

% now search cell arrays for given d, L and r to find Cthisd=0.005;thisL=2;thisr=0.001;% the index of L definesthe required row of the outer cell array% the index of d definesthe required column of the outer cell array% the index of r definesthe required row of the inner cell array% the capacitancevalues are in the fourth column of the inner cell arraythisC=mycapacá find(L==thisL),find(d==thisd)â á find(r==thisr),4 â ;fprintf('\nFrom cell array lookup, capacitance for:' ); 60

fprintf('\nd = %.3f m\nL = %.1f m\nr = %.3f m\nis %.3e F.\n' ,. . .thisd,thisL,thisr,thisC);

% check that lookup is correct by comparing with a direct function callfprintf('\nFrom direct function call, capacitance is %.3e F.\n' ,. . .

thiscap(thisd,thisL,thisr));% EOF

function c=thiscap(d,L,r)% THISCAP.M function to calculate capacitance% Palm Problem 3.24%% set permittivity of air (Faradsã m)perma=8.854e ä 12;% note c is undefinedif d=r or if (d-r) ã r=1if(d==r å (dä r) ã r==1)

c=NaN;else 10

btmline=log((dä r) ã r);c=piæ permaæ L ã btmline;

end% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

106

Page 115: MATLAB Short Course

A.3. Files,FunctionsandDataStructures

capac

From cell array lookup, capacitancefor:d = 0.005 mL = 2.0 mr = 0.001 mis 4.013e ç 011 F.

From direct function call, capacitanceis 4.013e ç 011 F.diary off 10

Problem 3.9,3.10

% BRIDGE.M script to assign bridge data to structure% Palm Problem 3.26%clear;clc;% fill data vectorslocstr(:,:)=['Smith St.' ;'Hope Ave.' ;'Clark St.' ;'North Rd.' ];maxload=[80, 90, 85, 100];yearbuilt=[1928, 1950, 1933, 1960];duemain=[1997, 1999, 1998, 1998]; 10

% assign structure array% Note this would be much easier to do in a for loopbridges(1).location=locstr(1,:);bridges(1).load=maxload(1);bridges(1).built=yearbuilt(1);bridges(1).due=duemain(1);%bridges(2).location=locstr(2,:);bridges(2).load=maxload(2);bridges(2).built=yearbuilt(2); 20

bridges(2).due=duemain(2);%bridges(3).location=locstr(3,:);bridges(3).load=maxload(3);bridges(3).built=yearbuilt(3);bridges(3).due=duemain(3);%bridges(4).location=locstr(4,:);bridges(4).load=maxload(4);bridges(4).built=yearbuilt(4); 30

bridges(4).due=duemain(4);%fprintf('\n Location Max load Year built Due' );fprintf('\n\n %10s %7d %10d %10d' ,bridges(1).location,bridges(1).load,.. .

bridges(1).built,bridges(1).due);fprintf('\n %10s %7d %10d %10d' ,bridges(2).location,bridges(2).load,.. .

bridges(2).built,bridges(2).due);

107

Page 116: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

fprintf('\n %10s %7d %10d %10d' ,bridges(3).location,bridges(3).load,.. .bridges(3).built,bridges(3).due);

fprintf('\n %10s %7d %10d %10d' ,bridges(4).location,bridges(4).load,.. . 40

bridges(4).built,bridges(4).due);% Problem 3.27bridges(3).due=2000;fprintf('\n\n Location Max load Year built Due' );fprintf('\n\n %10s %7d %10d %10d' ,bridges(1).location,bridges(1).load,.. .

bridges(1).built,bridges(1).due);fprintf('\n %10s %7d %10d %10d' ,bridges(2).location,bridges(2).load,.. .

bridges(2).built,bridges(2).due);fprintf('\n %10s %7d %10d %10d' ,bridges(3).location,bridges(3).load,.. .

bridges(3).built,bridges(3).due); 50

fprintf('\n %10s %7d %10d %10d' ,bridges(4).location,bridges(4).load,.. .bridges(4).built,bridges(4).due);

% Problem 3.28bridges(5).location='Shore Rd.' ;bridges(5).load=85;bridges(5).built=1997;bridges(5).due=2002;fprintf('\n\n Location Max load Year built Due' );fprintf('\n\n %10s %7d %10d %10d' ,bridges(1).location,bridges(1).load,.. .

bridges(1).built,bridges(1).due); 60

fprintf('\n %10s %7d %10d %10d' ,bridges(2).location,bridges(2).load,.. .bridges(2).built,bridges(2).due);

fprintf('\n %10s %7d %10d %10d' ,bridges(3).location,bridges(3).load,.. .bridges(3).built,bridges(3).due);

fprintf('\n %10s %7d %10d %10d' ,bridges(4).location,bridges(4).load,.. .bridges(4).built,bridges(4).due);

fprintf('\n %10s %7d %10d %10d\n' ,bridges(5).location,bridges(5).load,.. .bridges(5).built,bridges(5).due);

% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

bridge

Location Max load Year built Due

Smith St. 80 1928 1997Hope Ave. 90 1950 1999Clark St. 85 1933 1998North Rd. 100 1960 1998

Location Max load Year built Due 10

Smith St. 80 1928 1997Hope Ave. 90 1950 1999Clark St. 85 1933 2000North Rd. 100 1960 1998

Location Max load Year built Due

108

Page 117: MATLAB Short Course

A.4. Programmingwith MATLAB

Smith St. 80 1928 1997Hope Ave. 90 1950 1999 20

Clark St. 85 1933 2000North Rd. 100 1960 1998Shore Rd. 85 1997 2002diary off

A.4 Programming with MATLAB

Self-Test 4.1

(a) Sinceè hasall elementsnon-zero,éNè resultsin a1x4arrayof zeros.Only thesecondelementofê is lessthanzerohencetheresultwill be ë ìEí î í ìEí ì ï .(b) As theelementsof ê andthecorrespondingelementsof è arenon-zero,the resultwill be a 1x4

arrayof ones,i.e. ë î í î í î í î ï .(c) Comparingê and è element-by-element,at leastoneof thex, y pairsarenon-zerohencetheresult

is a1x4arrayof ones.

(d) Thecorrespondingelementsof ê andè arebothnon-zerosotheresultwill bea1x4arrayof zeros.

Self-Test 4.2

Thefunctionalrelationshipis plottedin FigureA.2.

Thefollowing pseudocodemightbesuitablefor theprimaryfunctionassociatedwith thisproblem:

% testvalidity of inputsif thesineof theangleis outsidetherange-1 to +1 or,if thequadrantis outsidetherange1 to 4, orif thequadrantis notawholenumber, orif thesineandquadrantareincompatible,then

print anerrormessageandexit theprogramend

109

Page 118: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

0 90 180 270 360

1 2 3 4

sin(

x)

x (degrees)

start of quadrant

FigureA.2: Plotof sin(x)

% assignangledirectly if givensineequalto +1, -1 or 0if thesineis equalto +1

settheangleto 90elseifthesineis equalto -1

settheangleto 270elseifthesineis equalto 0

if thequadrantis equalto 1settheangleto 0

elseifthequadrantis equalto 3settheangleto 180

endelse% useasin functionto calculatetheanglecalculatetheabsolutevalueof theangleif thequadrantis equalto 1

leave theangleasiselseifthequadrantis equalto 2

subtracttheanglefrom 180elseifthequadrantis equalto 3

addtheangleto 180elseifthequadrantis equalto 4

subtracttheanglefrom 360end

110

Page 119: MATLAB Short Course

A.4. Programmingwith MATLAB

Themainscriptandfunctionfile arereproducedbelow:

% MYSIN.M script to calculate angle in degrees for given quadrant and inverse sineclear;clc;% enter sine of angle and quadrant from keyboardthisdata=input('Enter sine of angle (-1 to +1) and quadrant (1-4) in square brackets. . .' );% print result to screenfprintf('\nAngle is %.2f degrees.\n' ,sinquad(thisdata));%% Print table to test validity of solution for each quadrant,% using valid range for each quadrant 10

fprintf('\nSample table follows:\n' );% first quadrantinvsin=[0 0.5 sqrt(3) ð 2 0.999];fprintf('\n\n sin(x) quadrant x(degrees)' );for(i=1:length(invsin))

fprintf('\n %6.3f %6d %14.1f' ,invsin(i),1,sinquad([invsin(i) 1]));end% secondquadrantinvsin=[1 sqrt(3) ð 2 0.5 0.001];fprintf('\n\n sin(x) quadrant x(degrees)' ); 20

for(i=1:length(invsin))fprintf('\n %6.3f %6d %14.1f' ,invsin(i),2,sinquad([invsin(i) 2]));

end% third quadrantinvsin=[0 ñ 0.5 ñ sqrt(3) ð 2 ñ 0.999];fprintf('\n\n sin(x) quadrant x(degrees)' );for(i=1:length(invsin))

fprintf('\n %6.3f %6d %14.1f' ,invsin(i),3,sinquad([invsin(i) 3]));end% fourth quadrant 30

invsin=[ñ 1 ñ sqrt(3) ð 2 ñ 0.5 ñ 0.001];fprintf('\n\n sin(x) quadrant x(degrees)' );for(i=1:length(invsin))

fprintf('\n %6.3f %6d %14.1f' ,invsin(i),4,sinquad([invsin(i) 4]));endfprintf('\n' );% EOF

function thisangle=sinquad(x);% SINQUAD.M calculatesangle in degrees for given sine and quadrant% x(1) is sine of angle; x(2) is quadrant%% check for real solution firstif(abs(x(1)) ò 1)

error('Inverse sine must be in the range -1 to +1' );end% check that quadrant is integer and inside valid rangeif(x(2) ò 4 ó x(2) ô 1 ó floor(x(2))˜=x(2)) 10

error('Quadrant must be an integer between 1 and 4' );end% check that given sine and quadrant are compatible

111

Page 120: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

errorflag=0;% sine must be in the range 0 õ = x(1) õ 1 in first quadrantif(x(2)==1 & (x(1) õ 0 ö x(1)==1))

errorflag=1;end% sine must be in the range 1 õ = x(1) õ 0 in secondquadrantif(x(2)==2 & x(1) õ =0) 20

errorflag=1;end% sine must be in the range 0 õ = x(1) õ -1 in third quadrantif(x(2)==3 & (x(1) ÷ 0 ö x(1)== ø 1))

errorflag=1;end% sine must be in the range -1 õ = x(1) õ 0 in fourth quadrantif(x(2)==4 & x(1) ÷ =0)

errorflag=1;end 30

if(errorflag)error('Given sine and quadrant are incompatible.' );

end% find angle in degreesif(x(1)==1)

thisangle=90;elseif(x(1)==ø 1)

thisangle=270;% sine is zero at 0 and 180 degrees

elseif(x(1)==0) 40

if(x(2)==1)thisangle=0;

elseif(x(2)==3)thisangle=180;

endelse

% ensure there is no negative angle otherwisethis% algorithm will give wrong answerthisangle=abs(asin(x(1)) ù (2 ú pi) ú 360);% subtract from 180 if in secondquadrant 50

if(x(2)==2)thisangle=180 ø thisangle;

elseif(x(2)==3)% add to 180 if in third quadrantthisangle=thisangle+180;

elseif(x(2)==4)% subtract from 360 if in fourth quadrantthisangle=360 ø thisangle;

endend 60

% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

mysinEnter sine of angle ( ø 1 to +1) and quadrant(1 ø 4) in squarebrackets. . .[ ø 0.8 4]

112

Page 121: MATLAB Short Course

A.4. Programmingwith MATLAB

Angle is 306.87 degrees.

Sampletable follows:

sin(x) quadrant x(degrees)0.000 1 0.0 10

0.500 1 30.00.866 1 60.00.999 1 87.4

sin(x) quadrant x(degrees)1.000 2 90.00.866 2 120.00.500 2 150.00.001 2 179.9

20

sin(x) quadrant x(degrees)0.000 3 180.0û 0.500 3 210.0û 0.866 3 240.0û 0.999 3 267.4

sin(x) quadrant x(degrees)û 1.000 4 270.0û 0.866 4 300.0û 0.500 4 330.0 30û 0.001 4 359.9diary off

Self-Test 4.3

% t443.m script for Palm self test 4.4-3clear;clc;k=1;% given FOR loopfprintf('\nFOR loop:' );for k=1:10

x1=50 û kˆ 2;if(x1 ü 0)

break; 10

endy1=sqrt(x1);fprintf('\nk is %.0f\t x1 is %.0f\t y1 is %.3f.' ,k,x1,y1);

end% equivalentWHILE loopk=1;fprintf('\n\nWHILE loop:' );while(kü =10)

x2=50 û kˆ 2;

113

Page 122: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

if(x2 ý =0) 20

y2=sqrt(x2);fprintf('\nk is %.0f\t x2 is %.0f\t y2 is %.3f.' ,k,x2,y2);

endk=k+1;

endfprintf('\n' );% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

t443

FOR loop:k is 1 x1 is 49 y1 is 7.000.k is 2 x1 is 46 y1 is 6.782.k is 3 x1 is 41 y1 is 6.403.k is 4 x1 is 34 y1 is 5.831.k is 5 x1 is 25 y1 is 5.000.k is 6 x1 is 14 y1 is 3.742.k is 7 x1 is 1 y1 is 1.000. 10

WHILE loop:k is 1 x2 is 49 y2 is 7.000.k is 2 x2 is 46 y2 is 6.782.k is 3 x2 is 41 y2 is 6.403.k is 4 x2 is 34 y2 is 5.831.k is 5 x2 is 25 y2 is 5.000.k is 6 x2 is 14 y2 is 3.742.k is 7 x2 is 1 y2 is 1.000.diary off 20

Thefollowing pseudocodemightbeappropriatefor thesecondproblem:

assignelementsof þ over anappropriaterangesetinitial valuefor relative differencebetweenÿ � and ÿ �approx.setinitial valuefor þ countersettolerancevaluewhile absoluterelative differenceexceedstolerancevalue:

calculateÿ �approx. for currentþ valuecalculaterelative differenceincrementcounterfor þ value

endprint results

% SAPPROX.M series approximation for e x% Palm self-testT4.4-4

114

Page 123: MATLAB Short Course

A.4. Programmingwith MATLAB

clear;clc;% set range for x vector, say 0-2% use incrementsof 0.005 as we need a result only to nearest 0.01x=0:0.005:2;% set tolerance at 1 percenttol=0.01;% set initial value for relative difference, must be less than tolerance 10

reldiff=tol�2;

% set initial value for x counterk=1;while(abs(reldiff) � tol)

% series approximation for e xexapprox=1+x(k)+x(k) 2

�2+x(k)ˆ 3

�6;

% find relative errorreldiff=(exapprox� exp(x(k)))

�exp(x(k));

% incrementx counterk=k+1; 20

end% counter for required x value is one less than current k value% print result to two decimal placesfprintf('\nLargest x value for error within %.1f%% is %.2f.\n' ,tol � 100,x(k � 1));% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

sapprox

Largest x value for error within 1.0% is 0.83.diary off

Problem 4.1

Pseudocodeasfollows:

initialisecost,income,numberboughtandnumbersoldto zerofor eachdayof simulation:

if thepriceis lessthan20incrementcostby 100timespriceincrementnumberboughtby 100

elseifthepriceis greaterthan25incrementincomeby 100timespriceincrementnumbersoldby 100

endendprint results

115

Page 124: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

% SHARES.M% Palm Problem 4.10clear;clc;% set share priceprice=[19 18 22 21 25 19 17 21 27 29];% initialise totalscost=0; income=0; bought=0; sold=0;% loop for each day of simulationfor(k=1:length(price)) 10

if(price(k)� 20)cost=cost+100 � price(k);bought=bought+100;

elseif(price(k)� 25)income=income+100 � price(k);sold=sold+100;

endend% print resultsfprintf('\nCost of buying shares is $%.0f' ,cost); 20

fprintf('\nReceipts from sale of shares is $%.0f' ,income);fprintf('\nNumber of shares held is %.0f' ,1000+bought� sold);% worth at start of period is 1000� price(1)% worth at end of period is (1000+bought-sold)� price(length(price))fprintf('\nNet increase in worth of portfolio is $%.0f' ,. . .

(1000+bought� sold)� price(length(price))� 1000 � price(1));% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

shares

Cost of buying sharesis $7300Receiptsfrom sale of sharesis $5600Number of sharesheld is 1200Net increasein worth of portfolio is $15800diary off

Problem 4.2

Theequationscanberearrangedsothat is thedependentvariable:

� � ���� ���� �� ����� � � �� ��� ��� ���� �

Pseudocodefollows:

116

Page 125: MATLAB Short Course

A.4. Programmingwith MATLAB

DEFLECT.M % functionfilefor eachvalueof :

if / !�" is lessthan #make $ equalto / !�"

elsemake $ equalto ( �%'& !�( # )/( !�")%�& ! ( )

endend

SPRING.M% mainscriptinput , !�" , ! ( and #calculatedeflectionfor givenscalar % call DEFLECT.Mprint resultcalculatedeflectionfor givenvector % call DEFLECT.Mplot results

function x=deflect(W,k1,k2,d)% calculatesdeflectionfor given weight and spring constants% W can be scalar or vector%% matrix algebra is more efficient than loop% find change of slope of x vs W plotchange=find(W* k1+ d);x(change)=W(change)* k1;x(max(change)+1:length(W))=(W(max(change)+1:length(W))+2 , k2, d)* (k1+2 , k2);% 10

% Alternative solution using FOR loop:%for(k=1:length(W))% if(W(k)* k1+ d)% x(k)=W(k)* k1;% else% x(k)=(W(k)+2, k2, d)* (k1+2, k2);% end%end% EOF

% SPRING.Mmain script for Palm Problem 4.14clear;clc;thedata=input('Enter W, k1, k2, d in square brackets. . .' );% calculate deflectionfor given scalar Wfprintf('\nDeflection under load of %.0f N is %.3f m' ,. . .

thedata(1),deflect(thedata(1),thedata(2),thedata(3),thedata(4)));% fill load vectorWvec=0:3000;% calculate deflectionfor given load vector 10

deflectvec=deflect(Wvec,thedata(2),thedata(3),thedata(4));% plot deflectionagainst loadfigure('Position' ,get(0,'ScreenSize' ));

117

Page 126: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

plot(Wvec,deflectvec,'r-' );xlabel('Load (N)' );ylabel('Deflection (m)' );title('Spring Load - Deflection Plot' );grid;pause;% Plot to PostScript file 20

orient landscape;print('-deps' ,'spring.eps' );close;% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

springEnter W, k1, k2, d in squarebrackets. . .[500 1e4 1.5e4 0.1]

Deflection under load of 500 N is 0.050 mdiary off

Thedeflection-loadplot is shown in FigureA.3.

Problem 4.3

Thecodefor thisproblemis fairly simplehencepseudocodeis probablyunwarranted.

function vs=supplyv(t)% supply voltage function for time vector tvs=3 - exp(. t / 3). - sin(pi.- t);% EOF

% DIODE1.M script for Palm Problem 4.17clear;clc;% set time domaint=0:0.01:10;% set load voltage for ideal diodevideal=supplyv(t);% set elementsless than zero equal to zerok=find(videal0 0);videal(k)=0; 10

% set load voltage for offset diodevoffset=supplyv(t);% subtract 0.6 from those elementsgreater than 0.6k=find(voffset1 0.6);l=find(voffset0 =0.6);% set elementsless than or equal to 0.6 to zerovoffset(k)=voffset(k). 0.6;

118

Page 127: MATLAB Short Course

A.4. Programmingwith MATLAB

0 500 1000 1500 2000 2500 30000

0.02

0.04

0.06

0.08

0.1

0.12

0.14

0.16

Load (N)

Def

lect

ion

(m)

Spring Load − Deflection Plot

FigureA.3: Plot for Problem4.2

voffset(l)=0;% plot voltage against timefigure('Position' ,get(0,'ScreenSize' )); 20

plot(t,videal,'b-' ,t,voffset,'r--' );xlabel('Time (s)' );ylabel('Load Voltage (V)' );title('Load Voltage - Time Relationship' );legend('Ideal Diode' ,'Offset Diode' );grid;pause;orient landscape;print('-deps' ,'diode1.eps' );close; 30

% EOF

Thevoltage-timeplot is shown in FigureA.4.

Problem 4.4

Thedevelopmentof appropriatepseudocodeand/orflowchartis left ananexercisefor thestudent.

119

Page 128: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

0 1 2 3 4 5 6 7 8 9 100

0.5

1

1.5

2

2.5

3

Time (s)

Load

Vol

tage

(V

)Load Voltage − Time Relationship

Ideal DiodeOffset Diode

FigureA.4: Plot for Problem4.3

% DISTCEN.MScript to determineand plot optimum location of distribution centre% Palm Problem 4.18clear;clc;global vol xcust ycust;% set coordinates and volumesfor each customerxcust=[1 7 8 17 22 27];ycust=[28 18 16 2 10 8];vol=[3 7 4 5 2 6];% use fminsearch to find minimum of cost function 10

cencoord=fminsearch('costfun' ,[1 1]);% plot cost function and resultscostplot(cencoord);% test sensitivity of location to costfprintf(' Distribution Centre Location and Cost\n\n' );fprintf(' x(miles) y(miles) Cost Change from Minimum Cost (%%)' );% set incrementat one miledistinc=1;coords=[cencoord(1) cencoord(2);. . .%at minimum point

cencoord(1) 2 distinc cencoord(2);. . .%one mile west 20

cencoord(1)+distinc cencoord(2);. . .%one mile east

120

Page 129: MATLAB Short Course

A.4. Programmingwith MATLAB

cencoord(1) cencoord(2)+distinc;.. .%one mile northcencoord(1) cencoord(2) 3 distinc];%one mile south

for(k=1:length(coords))costs(k)=costfun(coords(k,:));fprintf('\n %6.1f %10.1f %11.1f %14.1f' ,coords(k,1),coords(k,2),costs(k),.. .

(costs(k)3 costs(1)) 4 costs(1) 5 100);end% EOF

function totcost=costfun(x)% COSTFUN.Mfunction which determinestotal cost for Palm Problem 4.18% x(1) is x coordinate of distribution centre% x(2) is y coordinate of distribution centre% vol is vector of volumesfor each customer% xcust and ycust are vectors of x, y coordinates for customersglobal vol xcust ycust;% calculate distanceto each customerfor(k=1:length(xcust))

dist(k)=sqrt((xcust(k)3 x(1))ˆ 2+(ycust(k)3 x(2))ˆ 2); 10

end% calculate cost for each customerand then total costcustcost=0.5. 5 dist.5 vol;totcost=sum(custcost);% EOF

function costplot(costmincoord)% COSTPLOT.M plots cost function for distribution centre Palm Problem 4.18global vol xcust ycust;% set x and y values for plot; extend range by say 10%xvals=0:0.5:1.1 5 max(xcust);yvals=0:0.5:1.1 5 max(ycust);% calculate cost valuesfor(k=1:length(yvals))

for(m=1:length(xvals))costvals(k,m)=costfunct([xvals(m) yvals(k)]); 10

endend% plot cost function as 3D surfacefigure('Position' ,get(0,'ScreenSize' ));surf(xvals,yvals,costvals);xlabel('Easting (miles)' );ylabel('Northing (miles)' );zlabel('Cost' );mytitle=sprintf('Cost Function for Distribution Centre\nminimum is %.1f at (%.1f,%.1f)' ,. . .

costfunct(costmincoord),costmincoord(1),costmincoord(2)); 20

title(mytitle);grid on;pause;% output as PostScript graphicorient landscape;print('-deps' ,'cost3d.eps' );close;% now plot as labelled contour plot

121

Page 130: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

figure('Position' ,get(0,'ScreenSize' ));% set contour intervals 30

[C,h]=contour(xvals,yvals,costvals,[150:25:300]);% include contour labels for each intervalclabel(C,h);xlabel('Easting (miles)' );ylabel('Northing (miles)' );% sametitle as previoustitle(mytitle);% draw lines to minimum cost pointline([0 costmincoord(1) costmincoord(1)],[costmincoord(2) costmincoord(2) 0],. . .

'LineStyle' ,'--' ); 40

% place marker (a dot) at minimum cost pointline(costmincoord(1),costmincoord(2),'Marker' ,'.' ,'MarkerSize' ,15);grid on;pause;orient landscape;print('-deps' ,'costcont.eps' );close;% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

distcenDistribution Centre Location and Cost

x(miles) y(miles) Cost Changefrom Minimum Cost (%)8.5 16.1 147.2 0.07.5 16.1 149.7 1.79.5 16.1 147.6 0.38.5 17.1 148.7 1.18.5 15.1 148.8 1.1

diary off 10

Thesurfaceandcontourplotsof costfunctionagainstlocation(PostScriptgraphicsfilesCOST3D.EPSandCOSTCONT.EPS) areshown in FiguresA.5 andA.6 respectively.

122

Page 131: MATLAB Short Course

A.4. Programmingwith MATLAB

0

5

10

15

20

25

30

0

5

10

15

20

25

30

35100

150

200

250

300

350

400

Easting (miles)

Cost Function for Distribution Centreminimum is 147.2 at (8.5,16.1)

Northing (miles)

Cos

t

FigureA.5: SurfacePlot for Problem4.4

0 5 10 15 20 250

5

10

15

20

25

30

Easting (miles)

Nor

thin

g (m

iles)

Cost Function for Distribution Centreminimum is 147.2 at (8.5,16.1)

150

150

175

175

175

175175

200

200

200

200

200

200

200

225

22522

5

225

225

225

225

250250

250

250

250

250

275

275

275

275

300

FigureA.6: ContourPlot for Problem4.4

123

Page 132: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

Problem 4.5

% BANK1.M Script for Palm Problem 4.21clear;clc;% set annual depositdeposit=1e4;% set annual interest rate and target amountirate=6; target=1e6;% set initial amount and counter for loopamount=1e4;yearcount=0; 10

fprintf('\nYears elapsed Value ($1000s)' );while(amount6 target)

% calculate interest on amount held for 12 monthsinterest=amount7 irate8 100;% add interest, deposit and carryover capital at end of yearamount=amount+deposit+interest;% incrementyear counteryearcount=yearcount+1;fprintf('\n%8d %10.1f' ,yearcount,amount8 1000);

end 20

% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

bank1

Yearselapsed Value ($1000s)1 20.62 31.83 43.74 56.45 69.86 83.97 99.0 10

8 114.99 131.8

10 149.711 168.712 188.813 210.214 232.815 256.716 282.117 309.1 20

18 337.619 367.920 399.921 433.922 470.023 508.2

124

Page 133: MATLAB Short Course

A.4. Programmingwith MATLAB

24 548.625 591.626 637.127 685.3 30

28 736.429 790.630 848.031 908.932 973.433 1041.8

diary off

Problem 4.6

Thesix (6) simultaneousequationsgivencombinedwith thefirst of theconstraints(9;:=<?> @ A A ) maybewritten in matrix form as:BCCCCCCCCCCCCCC

D

>E>GFH>EFH>IAJFH>GFK>AMLEFH>EFONPAJF=QMFSRAEAT>P>GFK>IAMFK>AEAUAPVMFS@UAMFK>AEAUAPAT>P>GFK>AEAUAPAUAPVMFK>>WAUAPAUAPAPA

X YYYYYYYYYYYYYYZ

[

BCCCCCCCCCCCCCCD

9;:9]\9]^9`_9]a9]bc

X YYYYYYYYYYYYYYZ<

BCCCCCCCCCCCCCCD

AAAAAA> @ A A

X YYYYYYYYYYYYYYZ

(A.2)

Applying thesecondconstraint(9;\=<?> @ A A ):BCCCCCCCCCCCCCCD

>E>GFH>EFH>IAJFH>GFK>AMLEFH>EFONPAJF=QMFSRAEAT>P>GFK>IAMFK>AEAUAPVMFS@UAMFK>AEAUAPAT>P>GFK>AEAUAPAUAPVMFK>AJ>IAPAUAPAPA

X YYYYYYYYYYYYYYZ

[

BCCCCCCCCCCCCCCD

9;:9]\9]^9`_9]a9]bc

X YYYYYYYYYYYYYYZ<

BCCCCCCCCCCCCCCD

AAAAAA> @ A A

X YYYYYYYYYYYYYYZ

(A.3)

andthethird (9;^=<�N�A A ):BCCCCCCCCCCCCCCD

>G>GFK>GFH>dAMFK>GFH>AELEFK>GFONTAMFSQMF=RAGAe>U>GFK>IAJFH>AGAPAUVMFS@UAJFH>AGAPAUAe>U>EFH>AGAPAUAPAUVJFH>AGAe>IAPAUAPA

X YYYYYYYYYYYYYYZ

[

BCCCCCCCCCCCCCCD

9f:9;\9;^9]_9;a9;bc

X YYYYYYYYYYYYYYZ<

BCCCCCCCCCCCCCCD

AAAAAAN A A

X YYYYYYYYYYYYYYZ

(A.4)

125

Page 134: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

andthefourth (g]hSi�j�k k ):lmmmmmmmmmmmmmmn

oGoGpKoGpHo k pKoGpHokEq pKoGp jTk pSrMp=skGk oUoGpKo k pHokGkPkUt pSu k pHokGkPkUk oUoEpHokGkPkUkPkUt pHokGkPk o kUkPk

v wwwwwwwwwwwwwwx

y

lmmmmmmmmmmmmmmn

gfzg;{g;|g]hg;}g;~�

v wwwwwwwwwwwwwwxi

lmmmmmmmmmmmmmmn

kkkkkkj k k

v wwwwwwwwwwwwwwx

(A.5)

andthefifth (g;}=i u k k ):lmmmmmmmmmmmmmmn

oGoGpKoGpHo k pKoGpHokEq pKoGp jTk pSrMp=skGk oUoGpKo k pHokGkPkUt pSu k pHokGkPkUk oUoEpHokGkPkUkPkUt pHokGkPkUk o kPk

v wwwwwwwwwwwwwwx

y

lmmmmmmmmmmmmmmn

gfzg;{g;|g]hg;}g;~�

v wwwwwwwwwwwwwwxi

lmmmmmmmmmmmmmmn

kkkkkku k k

v wwwwwwwwwwwwwwx

(A.6)

andthesixth (g]~Si u k k ):lmmmmmmmmmmmmmmn

oGoGpKoGpHo k pKoGpHokEq pKoGp jTk pSrMp=skGk oUoGpKo k pHokGkPkUt pSu k pHokGkPkUk oUoEpHokGkPkUkPkUt pHokGkPkUkPk o k

v wwwwwwwwwwwwwwx

y

lmmmmmmmmmmmmmmn

gfzg;{g;|g]hg;}g;~�

v wwwwwwwwwwwwwwxi

lmmmmmmmmmmmmmmn

kkkkkku k k

v wwwwwwwwwwwwwwx

(A.7)

Eachof Eqns.A.2- A.7 canbesolvedindependentlyhowever only oneof thesesix solutionswill satisfythegivenconstraintssimultaneously. Suitablepseudocodemight be:

CABLE.Mfor eachof thesimultaneousequationsA.2 - A.7:

find thesolutionvectorenddeterminewhich one of the six solution vectorssatisfy the con-straintssimultaneouslyprint theappropriatevector

126

Page 135: MATLAB Short Course

A.4. Programmingwith MATLAB

% CABLE.M Statics Problem 4.23 Palmclear;clc;% solution of simultaneousequationsform AT=b% size cable tension vectorT=zeros(7,1);% columnsof matrix A are coefficients of T1,T2,T3,T4,T5,T6,W% rows representeach simultaneouseqn.A=[1, 1, � 1, � 1, 0, � 1, � 1;. . .

0, 7, � 1, � 4, 0, � 6, � 5;. . . 10

0, 0, 1, 1, � 1, 0, � 1;. . .0, 0, 0, 3, � 2, 0, � 1;. . .0, 0, 0, 0, 1, 1, � 1;. . .0, 0, 0, 0, 0, 3, � 1];

for(k=1:length(T)� 1)switch(k)case1

% add last row to A for T1=1200A(length(T),:)=[1, 0, 0, 0, 0, 0, 0];% b vector for T1=1200 20

b=[0, 0, 0, 0, 0, 0, 1200]';case2

% change last row of A for T2=1200A(length(T),:)=[0, 1, 0, 0, 0, 0, 0];% no modification to b vector needed

case3% change last row of A for T3=400A(length(T),:)=[0, 0, 1, 0, 0, 0, 0];% modify b vector for T3=400b=[0, 0, 0, 0, 0, 0, 400]'; 30

case4% change last row of A for T4=400A(length(T),:)=[0, 0, 0, 1, 0, 0, 0];% no modification to b vector needed

case5% change last row of A for T5=200A(length(T),:)=[0, 0, 0, 0, 1, 0, 0];% modify b vector for T5=200b=[0, 0, 0, 0, 0, 0, 200]';

case6 40

% change last row of A for T6=200A(length(T),:)=[0, 0, 0, 0, 0, 1, 0];% no modification to b vector needed

end% solve by matrix left divisionT(:,k)=A � b;

end% find column of T which satisfiesconstraints simultaneouslyfor(k=1:length(T)� 1)

if(T(1,k) � =1200 & T(2,k) � =1200 & T(3,k) � =400 & T(4,k) � =400 & T(5,k) � =200 & T(6,k) � =200) 50

soln=k;end

end

127

Page 136: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

% printf resultsfprintf('\nT1 = %.0fN\nT2 = %.0fN\nT3 = %.0fN\nT4 = %.0fN\nT5 = %.0fN\nT6 = %.0fN \nW = %.0fN' ,. . .

T(:,soln));% EOF

60

Theoutputfrom theMATLAB commandwindow is asfollows:

cable

T1 = 429NT2 = 471NT3 = 267NT4 = 233NT5 = 200NT6 = 100NW = 300Ndiary off 10

Problem 4.7

The function ��� �f� �`� is createdin a separatefunction file so that it may be called asmany times asrequiredvia a loop in the main script. The plotting routinesareplacedin a separatefunction file forconvenience.

% PLATE.M Script for Palm Problem 4.25clear;clc;% set coordscoord=[1, 1];% set plate dimensionsdimen=[2, 2];% set boundary tempsT1=70;T2=200; 10

% first task is to verify that absolutevalues of elementsof series% approximation becomesmaller as n increases(for centre of plate)n=19;[W, w]=fnxy(coord,dimen,n);smaller=zeros(size(w));fprintf('\nfor n = %2d (%2d terms) W = %8.5f:' ,n,length(w),W);for(k=1:length(w))

fprintf('\nTerm (%2d) is %15.10f' ,k,w(k));if(k � =2 & abs(w(k))� =abs(w(k� 1)))

smaller(k)=1; 20

endend

128

Page 137: MATLAB Short Course

A.4. Programmingwith MATLAB

% if elements2:length(w) of smaller vector are one then% elementsof w are decreasing in magnitudefprintf('\n\nAbsolute value of successive terms is ' );if(isempty(find(smaller(2:length(w)==0))))

fprintf('decreasing.' );else

fprintf('increasing.' );end 30

% next test sensitivity of temperature calculation to number of elements% set tolerance to toltol=0.01;% index for temperature loopcount=1;% flag to indicate when tolerance is reachedgotit=0;for(n=1:2:19)

[W, w]=fnxy(coord,dimen,n);T(count)=(T2� T1)� W+T1; 40

if(count � =2)deltaT=abs(T(count)� T(count� 1)) � T(count� 1);if(deltaT� tol & ˜gotit)

numterms=count;gotit=1;

endendcount=count+1;

endfprintf('\n\nAt least %1d terms are required for a precision of %.1f%%.' ,. . . 50

numterms,tol� 100);fprintf('\n\nTemperature at (%.1f,%.1f) is %.1fF.' ,coord(1),coord(2),T(numterms));% calculate temperatures on a gridinc gridgridinc=0.2;% initialise counter for outer loopx=1;% outer loop is for width (y direction - rows)% inner loop is for length (x direction - columns)for(k=0:gridinc:dimen(2))

% reset inner loop counter after each pass 60

y=1;for(m=0:gridinc:dimen(1))

% be careful with conditional logic!if(k==0 � (m==0 & k˜=dimen(2)) � (m==dimen(1) & k˜=dimen(2)))

gridT(x,y)=T1;elseif(k==dimen(2))

gridT(x,y)=T2;else

% three terms will be accurate enough[W, w]=fnxy([m k],dimen,3); 70

gridT(x,y)=(T2� T1)� W+T1;endy=y+1;

endx=x+1;

end% generate meshand contour plots

129

Page 138: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

tempplot([0:gridinc:dimen(1)],[0:gridinc:dimen(2)],gridT);% EOF

function [W, w]=fnxy(coord,dimen,n)% FNXY.M finds terms of series of, and functional value of, w(x,y) for given coords% and dimensions,Palm Problem 4.25% coord(1) is x dimension% coord(2) is y dimension% dimen(1) is plate length% dimen(2) is plate width% n is number of successiveapproximations% n must be odd numberif(˜rem(n,2)) 10

error('n must be an odd number' );end% set counter for terms of wcount=1;for(k=1:2:n)

w(count)=2 � k � sin((k� pi � coord(1)) � dimen(1)) � . . .sinh(k� pi � coord(2) � dimen(1)) � sinh(k� pi � dimen(2) � dimen(1));

count=count+1;endW=2 � pi � sum(w); 20

% EOF

function tempplot(xdata,ydata,zdata)% TEMPPLOT.M plots temperature distribution Palm Problem 4.25%% plot temperature as 3D meshfirstfigure('Position' ,get(0,'ScreenSize' ));mesh(xdata,ydata,zdata);xlabel('x (ft)' );ylabel('y (ft)' );zlabel('Temperature (F)' );mytitle=sprintf('Temperature Distribution For Flat Plate' ); 10

title(mytitle);grid on;pause;orient landscape;print('-deps' ,'tmesh3d.eps' );close;% now plot as labelled contour plotfigure('Position' ,get(0,'ScreenSize' ));% set contour interval at contintcontint=20; 20

[C,h]=contour(xdata,ydata,zdata,[min(min(zdata)):contint:max(max(zdata))]);% include contour labels for each intervalclabel(C,h);xlabel('x (ft)' );ylabel('y (ft)' );% sametitle as previoustitle(mytitle);grid on;

130

Page 139: MATLAB Short Course

A.4. Programmingwith MATLAB

pause;orient landscape; 30

print('-deps' ,'tempcont.eps' );close;% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

plate

for n = 19 (10 terms) W = 0.25000:Term ( 1) is 0.3985368153Term ( 2) is � 0.0059883774Term ( 3) is 0.0001552813Term ( 4) is � 0.0000047931Term ( 5) is 0.0000001611Term ( 6) is � 0.0000000057Term ( 7) is 0.0000000002 10

Term ( 8) is � 0.0000000000Term ( 9) is 0.0000000000Term (10) is � 0.0000000000

Absolute value of successive terms is decreasing.

At least 2 terms are required for a precision of 1.0%.

Temperatureat (1.0,1.0) is 102.5F.diary off 20

Successive termsof the ��� �f� �`� seriesaretestedby theprogramto seeif they areconsistentlydecreasingin absolutemagnitude.Eachsuccessive termsalternatesbetweenpositive andnegative signsin accor-dancewith sin(n � ). Thecalculatedtemperatureof 102.5� F is reasonablegiventhepointcoordinatesandboundarytemperatures.

Thesurfaceandcontourplotsof temperature(PostScriptgraphicsfilesTMESH3D.EPS andTEMPCONT.EPS) areshown in FiguresA.7 andA.8 respectively.

131

Page 140: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

00.2

0.40.6

0.81

1.21.4

1.61.8

2

0

0.5

1

1.5

260

80

100

120

140

160

180

200

x (ft)

Temperature Distribution For Flat Plate

y (ft)

Tem

pera

ture

(F

)

FigureA.7: SurfacePlot for Problem4.7

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 20

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

2

x (ft)

y (f

t)

Temperature Distribution For Flat Plate

90

90

90

90

90

110

110

110

110130

130 130

130

150

150 150

150170

170

170

190190 190

FigureA.8: ContourPlot for Problem4.7

132

Page 141: MATLAB Short Course

A.4. Programmingwith MATLAB

Problem 4.8

pass k b x y

1 1 -2 -1 -2

2 2 -2 0 -2

3 3 -3 1 -3

Only threepasseswill bemadethroughthe loop. Theoutputfrom theMATLAB commandwindow isasfollows:

k =1

b = �2

x = �1

y = �2

k =2 10

b = �2

x =0

y = �2

k =3

b = �3 20

x =1

y = �3

diary off

Problem 4.9

% STATICF.M Script for Palm Problem 4.28clear;clc;% print menuwhich1=menu('Enter materials for static friction force' ,. . .

'Metal on metal' ,'Wood on wood' ,'Metal on wood' ,. . .'Rubber on concrete' );

wt=input('Enter weight W(N). . .' );switch(which1)case1 10

mu=0.20;

133

Page 142: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

case2mu=0.35;

case3mu=0.40;

case4mu=0.70;

endfprintf('\n\nStatic friction force is %.1f N.' ,mu  wt);% EOF 20

Problem 4.10

A samplescriptincorporatingonly themainloop is shown here.

% CARTS.MScript for Palm Problem 4.34clear;clc;S=[50,55,60,70,70,75,80,80,90,55];P(1)=50;I(1)=50;for(k=1:length(S))

if(k ¡ 1)P(k)=S(k¢ 1);

end 10

I(k+1)=P(k)+I(k)¢ S(k);end% EOF

A.5 Plotting and Model Building

Problem 5.3

% p507.mPalm Problem 5.7clear;clc;A=[0, ¢ 8, 6; 5, ¢ 4, 3; 10, ¢ 1, 1; 15, 1, 0; 20, 2, ¢ 1];figure('Position' ,get(0,'ScreenSize' ));plot(A(:,1),A(:,2),'rs' ,A(:,1),A(:,3),'g*' ,A(:,1),A(:,2),'r-' ,A(:,1),A(:,3),'g --' );xlabel('Time (s)' );ylabel('Force (N)' );title('Force - Time Relationship' );grid; 10

label1='Column 1' ;label2='Column 2' ;legend(label1,label2);pause;

134

Page 143: MATLAB Short Course

A.5. PlottingandModelBuilding

orient landscape;print('-deps' ,'p507.eps' );close;% EOF

Theplot is shown in FigureA.9.

0 2 4 6 8 10 12 14 16 18 20−8

−6

−4

−2

0

2

4

6

Time (s)

For

ce (

N)

Force − Time Relationship

Column 1Column 2

FigureA.9: Plot for Problem5.3

Problem 5.4

% traj.m Ball Trajectory Problem 5.16 Palmclear;clc;% gravitational accelerationg=9.81;% set large range on time vector to cover enoughflying timet=[0:0.1:100];% initial velocity vectorv=[10, 12, 14, 16, 18];% initial angle vector 10

iniangle=[20, 30, 35, 45, 60, 70];% find roots of quadratic for part (a) i.e. valuesof t for ht=0

135

Page 144: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

htcoeffs=[ £ 0.5 ¤ g, v(1) ¤ sin(iniangle(3) ¥ 360 ¤ 2 ¤ pi), 0];% find flying timetrange=roots(htcoeffs);% set time ranget=[min(trange):0.001:max(trange)];% calculate height over time rangeht=v(1). ¤ t ¤ sin(iniangle(3) ¥ 360 ¤ 2 ¤ pi) £ 0.5 ¤ g.¤ t.ˆ 2;% calculate distanceover time range 20

dist=v(1). ¤ t ¤ cos(iniangle(3) ¥ 360 ¤ 2 ¤ pi);% print required outputmytitle=sprintf('\nTrajectory for Initial Angle %.0f degrees, Initial Velocity %.0f m/s' ,. . .

iniangle(3),v(1));fprintf('\n %s' ,mytitle);fprintf('\nMaximum height is %.2f m.' ,max(ht));fprintf('\nMaximum distance is %.2f m.' ,max(dist));fprintf('\nTime to hit ground is %.2f s.' ,max(trange));% plot height against distancefigure('Position' ,get(0,'ScreenSize' )); 30

subplot(2,2,1);plot(dist,ht,'r-' );xlabel('Distance (m)' );ylabel('Height (m)' );title(mytitle);grid;subplot(2,2,2);hold on;% calculate trajectories for all angles with v=10% using samealgorithm as before 40

for(k=1:length(iniangle))t=[0:0.1:100];htcoeffs=[ £ 0.5 ¤ g, v(1) ¤ sin(iniangle(k)¥ 360 ¤ 2 ¤ pi), 0];trange=roots(htcoeffs);t=[min(trange):0.001:max(trange)];ht=v(1). ¤ t ¤ sin(iniangle(k)¥ 360 ¤ 2 ¤ pi) £ 0.5 ¤ g.¤ t.ˆ 2;dist=v(1). ¤ t ¤ cos(iniangle(k)¥ 360 ¤ 2 ¤ pi);% vary line width for non-colour printingplot(dist,ht,'LineStyle' ,'-' ,'LineWidth' ,k¥ 3);mylegend(k,:)=sprintf('%.0f deg.' ,iniangle(k)); 50

endxlabel('Distance (m)' );ylabel('Height (m)' );grid;mytitle=sprintf('Trajectories for Initial Velocity %.0f m/s' ,v(1));title(mytitle);legend(mylegend);% clear legend string otherwisemay causeproblemsif% strings for next plot are different lengthsclear mylegend; 60

subplot(2,2,3);hold on;% calculate trajectories for all velocities with A=45% samealgorithm as beforefor(k=1:length(v))

t=[0:0.1:100];htcoeffs=[ £ 0.5 ¤ g, v(k) ¤ sin(iniangle(4) ¥ 360 ¤ 2 ¤ pi), 0];

136

Page 145: MATLAB Short Course

A.5. PlottingandModelBuilding

trange=roots(htcoeffs);t=[min(trange):0.001:max(trange)];ht=v(k).¦ t ¦ sin(iniangle(4) § 360 ¦ 2 ¦ pi) ¨ 0.5 ¦ g.¦ t.ˆ 2; 70

dist=v(k).¦ t ¦ cos(iniangle(4) § 360 ¦ 2 ¦ pi);plot(dist,ht,'LineStyle' ,'-' ,'LineWidth' ,k§ 3);mylegend(k,:)=sprintf('%.0f m/s' ,v(k));

endxlabel('Distance (m)' );ylabel('Height (m)' );grid;mytitle=sprintf('Trajectories for Initial Angle %.0f degrees' ,iniangle(4));title(mytitle);legend(mylegend); 80

hold off;pause;% send to PostScript graphic outputorient landscape;print('-deps' ,'traj.eps' );close;% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

traj

Trajectory for Initial Angle 35 degrees, Initial Velocity 10 m§ sMaximum height is 1.68 m.Maximum distanceis 9.58 m.Time to hit ground is 1.17 s.diary off

Therequiredplotsareshown in FigureA.10.

Problem 5.5

% xyfit.m Script for Palm Problem 5.24clear;clc;% put all data for parts (a) to (c) in cell array for easy retrievalx= © [25, 30, 35, 40, 45],[2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 7, 8, 9, 10],[550:50:750] ª ;y= © [5, 260, 480, 745, 1100],[1500, 1220, 1050, 915, 810, 745, 690, 620, 520, 480, 410, 390],. . .

[41.2, 18.62, 8.62, 3.92, 1.86] ª ;% part (a)% plot relationship to determineif linear, exponential or power functionfigure('Position' ,get(0,'ScreenSize' )); 10

% linearsubplot(2,2,1);plot(x© 1 ª ,y © 1 ª ,'o' ,x © 1 ª ,y © 1 ª ,'-' );title('Linear' );

137

Page 146: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

0 2 4 6 8 100

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

Distance (m)

Hei

ght (

m)

Trajectory for Initial Angle 35 degrees, Initial Velocity 10 m/s

0 2 4 6 8 10 120

1

2

3

4

5

Distance (m)

Hei

ght (

m)

Trajectories for Initial Velocity 10 m/s

20 deg.30 deg.35 deg.45 deg.60 deg.70 deg.

0 5 10 15 20 25 30 350

1

2

3

4

5

6

7

8

9

Distance (m)

Hei

ght (

m)

Trajectories for Initial Angle 45 degrees

10 m/s12 m/s14 m/s16 m/s18 m/s

FigureA.10: TrajectoryPlotsfor Problem5.4

xlabel('x' );ylabel('y' );grid;% exponentialsubplot(2,2,2)semilogy(x« 1 ¬ ,y « 1 ¬ ,'o' ,x « 1 ¬ ,y « 1 ¬ ,'-' ); 20

xlabel('x' );ylabel('y' );title('Exponential' );grid;% powersubplot(2,2,3)loglog(x« 1 ¬ ,y « 1 ¬ ,'o' ,x « 1 ¬ ,y « 1 ¬ ,'-' );xlabel('x' );ylabel('y' );title('Power' ); 30

grid;pause;close;% from inspection,linear function appears best fit% calculate line of best fit and coeff. of determinationcoeffsa=polyfit(x« 1 ¬ ,y « 1 ¬ ,1);SSE=sum((polyval(coeffsa,x« 1 ¬ ) ­ y « 1 ¬ ).ˆ 2);

138

Page 147: MATLAB Short Course

A.5. PlottingandModelBuilding

SST=sum((y® 1 ¯ ° mean(y® 1 ¯ )).ˆ 2);r2a=1 ° SSE± SST;fprintf('\n(a) Coefficients for linear regression Y=Mx+B are:' ); 40

fprintf('\nM = %.2f B = %.2f (rˆ2 = %.4f)\n' ,coeffsa(1),coeffsa(2),r2a);% part (b)figure('Position' ,get(0,'ScreenSize' ));% linearsubplot(2,2,1);plot(x® 2 ¯ ,y ® 2 ¯ ,'o' ,x ® 2 ¯ ,y ® 2 ¯ ,'-' );title('Linear' );xlabel('x' );ylabel('y' );grid; 50

% exponentialsubplot(2,2,2)semilogy(x® 2 ¯ ,y ® 2 ¯ ,'o' ,x ® 2 ¯ ,y ® 2 ¯ ,'-' );title('Exponential' );xlabel('x' );ylabel('y' );grid;% powersubplot(2,2,3)loglog(x® 2 ¯ ,y ® 2 ¯ ,'o' ,x ® 2 ¯ ,y ® 2 ¯ ,'-' ); 60

xlabel('x' );ylabel('y' );title('Power' );grid;pause;close;% from inspection,power function appears best fit% calculate line of best fit and coeff. of determinationcoeffsb=polyfit(log10(x® 2 ¯ ),log10(y® 2 ¯ ),1);SSE=sum((10ˆ coeffsb(2). ² x ® 2 ¯ .ˆ coeffsb(1) ° y ® 2 ¯ ).ˆ 2); 70

SST=sum((y® 2 ¯ ° mean(y® 2 ¯ )).ˆ 2);r2b=1 ° SSE± SST;fprintf('\n(b) Coefficients for power regression Y=MxˆB are:' );fprintf('\nM = %.1f B = %.3f (rˆ2 = %.4f)\n' ,10ˆ coeffsb(2),coeffsb(1),r2b);% part (c)figure('Position' ,get(0,'ScreenSize' ));% linearsubplot(2,2,1);plot(x® 3 ¯ ,y ® 3 ¯ ,'o' ,x ® 3 ¯ ,y ® 3 ¯ ,'-' );title('Linear' ); 80

xlabel('x' );ylabel('y' );grid;% exponentialsubplot(2,2,2)semilogy(x® 3 ¯ ,y ® 3 ¯ ,'o' ,x ® 3 ¯ ,y ® 3 ¯ ,'-' );title('Exponential' );xlabel('x' );ylabel('y' );grid; 90

% powersubplot(2,2,3)

139

Page 148: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

loglog(x³ 3 ´ ,y ³ 3 ´ ,'o' ,x ³ 3 ´ ,y ³ 3 ´ ,'-' );xlabel('x' );ylabel('y' );title('Power' );grid;pause;close;% from inspection,could be power or exponential function 100

% calculate line of best fit and coeff. of determinationfor each% power firstcoeffsc1=polyfit(log10(x³ 3 ´ ),log10(y³ 3 ´ ),1);SSE=sum((10ˆ coeffsc1(2). µ x ³ 3 ´ .ˆ coeffsc1(1) ¶ y ³ 3 ´ ).ˆ 2);SST=sum((y³ 3 ´ ¶ mean(y³ 3 ´ )).ˆ 2);r2c1=1 ¶ SSE· SST;fprintf('\n(c) Coefficients for power regression Y=MxˆB are:' );fprintf('\nM = %.3g B = %.3f (rˆ2 = %.4f)\n' ,10ˆ coeffsc1(2),coeffsc1(1),r2c1);% now exponentialcoeffsc2=polyfit(x³ 3 ´ ,log10(y³ 3 ´ ),1); 110

SSE=sum((10ˆ coeffsc2(2) µ 10.ˆ (x ³ 3 ´ µ coeffsc2(1)) ¶ y ³ 3 ´ ).ˆ 2);r2c2=1 ¶ SSE· SST;fprintf('\n(c) Coefficients for exponential regression Y=B*10ˆMx are:' );fprintf('\nM = %.3g B = %.3g (rˆ2 = %.4f)\n' ,coeffsc2(1),10ˆ coeffsc2(2),r2c2);% now plot fitted curvesfigure('Position' ,get(0,'ScreenSize' ));% part (a)subplot(2,2,1);plot(x³ 1 ´ ,y ³ 1 ´ ,'o' ,x ³ 1 ´ ,polyval(coeffsa,x³ 1 ´ ),'-' );title('Part (a)' ); 120

mylegend=sprintf('Linear fit rˆ2 = %.4f' ,r2a);legend('Data' ,mylegend,0);xlabel('x' );ylabel('y' );grid;% part (b)subplot(2,2,2);plot(x³ 2 ´ ,y ³ 2 ´ ,'o' ,x ³ 2 ´ ,10ˆ coeffsb(2). µ x ³ 2 ´ .ˆ coeffsb(1),'-' );title('Part (b)' );mylegend=sprintf('Power fit rˆ2 = %.4f' ,r2b); 130

legend('Data' ,mylegend,0);xlabel('x' );ylabel('y' );grid;% part (c)subplot(2,2,3);plot(x³ 3 ´ ,y ³ 3 ´ ,'o' ,x ³ 3 ´ ,10ˆ coeffsc1(2). µ x ³ 3 ´ .ˆ coeffsc1(1),'-' ,. . .

x ³ 3 ´ ,10ˆ coeffsc2(2) µ 10.ˆ (x ³ 3 ´ µ coeffsc2(1)),'--' );title('Part (c)' );mylegend1=sprintf('Power fit rˆ2 = %.4f' ,r2c1); 140

mylegend2=sprintf('Exponential fit rˆ2 = %.4f' ,r2c2);legend('Data' ,mylegend1,mylegend2,0);xlabel('x' );ylabel('y' );grid;pause;orient landscape;

140

Page 149: MATLAB Short Course

A.5. PlottingandModelBuilding

print('-deps' ,'xyfit.eps' );close;% EOF 150

Theoutputfrom theMATLAB commandwindow is asfollows:

xyfit

(a) Coefficients for linear regressionY=Mx+B are:M = 53.50 B = ¸ 1354.50 (rˆ 2 = 0.9919)

(b) Coefficients for power regressionY=Mxˆ B are:M = 3582.1 B = ¸ 0.976 (rˆ 2 = 0.9982)

(c) Coefficients for power regressionY=Mxˆ B are:M = 1.06e+029 B = ¸ 9.995 (rˆ 2 = 0.9955) 10

(c) Coefficients for exponential regressionY=B ¹ 10ˆ Mx are:M = ¸ 0.00673 B = 2.06e+005 (rˆ 2 = 0.9998)diary off

A plot of thedataandfitted regressioncurvesareshown in FigureA.11.

For Part (c), theregressioncoefficientsfor thepower functionfit aretoounstableandthis functionis notrecommendedfor predictive purposes.For typicalvaluesof º theterm º]»�¼�º;½;¾ ¿ becomesaverysmallnumberandthecoefficient À is thereforea very large numberto compensate.Thesenumbersaretooextreme,perhapsbeyond thenumericalaccuracy of mosthandcalculators.Theexponentialregressionequationis recommendedfor Part (c).

Problem 5.6

% SPRING2.MScript for Palm Problem 5.30clear;clc;% force vectorf=[0, 0.47, 1.15, 1.64];% spring length vectory=[4.7, 7.2, 10.6, 12.9];% set length in terms of elongationy=y ¸ y(1);% plot relationship to determineif linear or power function 10

% note the exponential function cannot pass through originfigure('Position' ,get(0,'ScreenSize' ));% linearsubplot(1,2,1);plot(y,f,'o' ,y,f,'-' );title('Linear' );ylabel('Force' );

141

Page 150: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

25 30 35 40 45−200

0

200

400

600

800

1000

1200Part (a)

x

y

DataLinear fit r2 = 0.9919

2 4 6 8 10200

400

600

800

1000

1200

1400

1600Part (b)

x

y

DataPower fit r2 = 0.9982

550 600 650 700 7500

5

10

15

20

25

30

35

40

45Part (c)

x

y

DataPower fit r2 = 0.9955Exponential fit r2 = 0.9998

FigureA.11: RegressionPlotsfor Problem5.5

xlabel('Elongation' );grid;% power 20

subplot(1,2,2)loglog(y,f,'o' ,y,f,'-' );title('Power' );ylabel('Force' );xlabel('Elongation' );grid;pause;close;% from inspectionboth functions approximate a straight line% If the power function is to pass through the origin then 30

% B=1 in y=Mxˆ B and power function becomeslinear in any case% From derivation in Study Guide M=sum(xÁ y) sum(x 2)M=sum(y.Á f)  sum(y. 2);% plot regressionand calculate rˆ 2fpred=polyval([M 0],y,1);SSE=sum((fà fpred). 2);SST=sum((fà mean(f)). 2);r2=1 à SSE SST;figure('Position' ,get(0,'ScreenSize' ));plot(y,f,'o' ,y,fpred,'-' ); 40

142

Page 151: MATLAB Short Course

A.5. PlottingandModelBuilding

title('Spring Calibration' );ylabel('Force (lbs)' );xlabel('Elongation (in)' );mylegend=sprintf('Linear fit: rˆ2 = %.4f (M = %.3f lb/in)' ,r2,M);legend('Data' ,mylegend,0);grid;pause;orient landscape;print('-deps' ,'spring2.eps' );close; 50

% EOF

A plot of thedataandline of bestfit areshown in FigureA.12.

0 1 2 3 4 5 6 7 8 90

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8Spring Calibration

For

ce (

lbs)

Elongation (in)

DataLinear fit: r2 = 0.9992 (M = 0.198 lb/in)

FigureA.12: RegressionPlot for Problem5.6

Problem 5.7

% BRAKES.MPalm Problem 5.32clear;clc;% initialise data

143

Page 152: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

v=[20:10:70];d=[45, 80, 130, 185, 250, 330];% The situation is such that the regressioncurve% should pass through the origin becausethe stopping% distancefor zero speedis zero% From Study Guide problem involves solution 10

% of two simultaneousequationsin two unknownsin% the form Ax=b% Coefficient matrix (A) is [sum(x 4), sum(x 3); sum(x 3), sum(x 2)]A=[sum(v. 4), sum(v. 3); sum(v. 3), sum(v. 2)];% right hand side vector (b) is [sum(yÄ xˆ 2); sum(yÄ x)]b=[sum(d.Ä v.ˆ 2); sum(d.Ä v)];% solve by left divisioncoeffs=AÅ b;% find goodnessof fit indicators% regressionequation is form Cx 2+Mx 20

dpred=coeffs(1) Ä v.ˆ 2+coeffs(2) Ä v;SSE=sum((dpredÆ d). 2);SST=sum((dÆ mean(d)). 2);r2=1 Æ SSEÇ SST;% augmentplotting vectors to show regressioncurve passes% through originxplot=[0, 10, v];yplot=coeffs(1) Ä xplot. 2+coeffs(2) Ä xplot;figure('Position' ,get(0,'ScreenSize' ));plot(v,dpred,'o' ,xplot,yplot,'-' ); 30

xlabel('Speed v (mph)' );ylabel('Stopping Distance d (ft)' );mytitle=sprintf('Quadratic fit through origin: d = %.4f *vˆ2 + %.4f v (SSE = %.1f ftˆ2, SST = %.0f ftˆ2)' ,. . .

coeffs(1),coeffs(2),SSE,SST);title(mytitle);mylegend=sprintf('fit rˆ2 = %.4f' ,r2);legend('Data' ,mylegend,0);grid;pause;orient landscape; 40

print('-deps' ,'brakes.eps' );close;% EOF

A quadraticregressionfit throughtheorigin is shown in FigureA.13.

Problem 5.8

% TWISTS.MPalm Problem 5.34clear;clc;% initialise datay=[40, 51, 65, 72, 38, 46, 53, 67, 31, 39, 48, 56];x=[1:4, 1:4, 1:4; ones(1,4), ones(1,4). Ä 2, ones(1,4). Ä 3];% multiple linear regression

144

Page 153: MATLAB Short Course

A.5. PlottingandModelBuilding

0 10 20 30 40 50 60 700

50

100

150

200

250

300

350

Speed v (mph)

Sto

ppin

g D

ista

nce

d (f

t)Quadratic fit through origin: d = 0.0497 *v2 + 1.2169 v (SSE = 10.8 ft2, SST = 57550 ft2)

Datafit r2 = 0.9998

FigureA.13: RegressionPlot for Problem5.7

% From Study Guide problem involves solution% of length(y) simultaneousequationsin three unknownsin% the form Ax=b 10

% Coefficient matrix (A) has x1 data in first column, x2 data% in secondcolumn and ones in third columnA=[x(1,:); x(2,:); ones(1,length(y))]';% right hand side vector (b) has y data in one columnb=y';% solve by left divisioncoeffs=AÈ b;% find goodnessof fit indicators% regressionequation is form M1x1+M2x2+Bypred=coeffs(1). É x(1,:)+coeffs(2). É x(2,:)+coeffs(3); 20

SSE=sum((ypredÊ y).ˆ 2);SST=sum((yÊ mean(y)). 2);r2=1 Ê SSEË SST;% find largest positive or negative errormaxerror=max(abs(ypredÊ y));% find index for maximumerror to calculate percentage errorthisy=find(abs(ypredÊ y)==maxerror);% print resultsfprintf('\nMultiple linear regression Y=M1*x1 + M2*x2 + B:' );fprintf('\nM1 = %.3f\nM2 = %.3f\nB = %.1f\nSSE = %.1f\nSST = %.0f\nrˆ2 = %.4f' ,. . . 30

145

Page 154: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

coeffs,SSE,SST,r2);fprintf('\nMaximum absolute percentage error is %.2f%% at predicted y value of %.2f' ,. . .

maxerrorÌ y(thisy)Í 100,ypred(thisy));% EOF

Theoutputfrom theMATLAB commandwindow is asfollows:

Multiple linear regressionY=M1 Í x1 + M2 Í x2 + B:M1 = 9.600M2 = Î 6.750B = 40.0SSE = 40.1SST = 1787rˆ 2 = 0.9776Maximum absolutepercentageerror is 4.54% at predicted y value of 62.05diary off 10

Problem 5.9

% HELIX.M Script for Palm Problem 5.43clear;clc;% initialise datat=0:pi Ì 20:10 Í pi;a=1;x=a.Í cos(t);y=a.Í sin(t);b=[0.1, 0.2, Î 0.1];% set z axis for each plot to samescaling for better visual comparison 10

zrange=[min(min(b).Í t), max(max(b).Í t)];plotinc=piÌ 2;% set strings for z axis labels in incrementsof plotincm=1;for(k=zrange(1):plotinc:zrange(2))

% pad strings with leading blanks so each is samesizezstr(m,:)=sprintf('%5.1f*pi' ,kÌ pi);m=m+1;

end% plot helix for each of three cases 20

figure('Position' ,get(0,'ScreenSize' ));for(k=1:length(b))

% one row for subplotsshould be enoughsubplot(1,length(b),k);plot3(x,y,b(k).Í t,'r-' ,'LineWidth' ,6)if(k==1)

% get current viewpoint for graphmyview=get(gca,'CameraPosition' );% and drop z coord for better visualisationmyview(3)=myview(3) Ì 2; 30

146

Page 155: MATLAB Short Course

A.5. PlottingandModelBuilding

endset(gca,'ZLim' ,zrange);set(gca,'ZTick' ,zrange(1):plotinc:zrange(2));set(gca,'ZTickLabel' ,zstr);xlabel('x' );ylabel('y' );zlabel('z' );mytitle=sprintf('Helix for b = %.1f' ,b(k));title(mytitle);grid; 40

% set viewpointset(gca,'CameraPosition' ,myview);

endpause;orient landscape;print('-deps' ,'helix.eps' );close;% EOF

Therequiredplotsareshown in FigureA.14.

−10

1

−1

0

1

−1.0*pi

−0.5*pi

0.0*pi

0.5*pi

1.0*pi

1.5*pi

2.0*pi

x

Helix for b = 0.1

y

z

−10

1

−1

0

1

−1.0*pi

−0.5*pi

0.0*pi

0.5*pi

1.0*pi

1.5*pi

2.0*pi

x

Helix for b = 0.2

y

z

−10

1

−1

0

1

−1.0*pi

−0.5*pi

0.0*pi

0.5*pi

1.0*pi

1.5*pi

2.0*pi

x

Helix for b = −0.1

y

z

FigureA.14: 3D Plot for Problem5.9

147

Page 156: MATLAB Short Course

AppendixA. ModelSolutionsfor Self-TestsandTutorialProblems

Problem 5.10

% OSCILL.M Script for Palm Problem 5.49clear;clc;% initialise datat=0:0.1:15;tau=0.5:0.1:10;% generate meshfor surfaceplot[T,TAU]=meshgrid(t,tau);Z=exp(Ï T.Ð TAU). Ñ sin(2. Ñ T);figure('Position' ,get(0,'ScreenSize' )); 10

% combinedsurface and countour plotmeshc(T,TAU,Z);% get current viewpointmyview=get(gca,'CameraPosition' );% and shift down to show contours a little bettermyview(3)=myview(3) Ð 2;xlabel('t (sec)' );ylabel('\tau (sec)' );zlabel('z' );% set new viewpoint 20

set(gca,'CameraPosition' ,myview);grid on;title('Plot of eˆ{-t/\tau} sin(2t)' );pause;orient landscape;print('-deps' ,'oscill.eps' );close;% EOF

Thesurfaceandcontourplotsareshown in FigureA.15. Trendsareevidentfrom thesurfaceplot hencethereis no realadvantagein labellingthecontours.

148

Page 157: MATLAB Short Course

A.5. PlottingandModelBuilding

0

5

10

15

0

2

4

6

8

10

−0.

8

−0.

6

−0.

4

−0.

20

0.2

0.4

0.6

0.81

t (se

c)

Plo

t of e

−t/τ

sin

(2t)

τ (s

ec)

z

FigureA.15: 3D Plot for Problem5.10

149