You are on page 1of 213

ME232A VBAandMATLAB/Octave VBA and MATLAB/Octave Applications

Introduction
Purposeandapproach Purpose and approach Syllabusreview Courserequirements C i Courseoutline

ME232A:EngineeringDigitalComputationsActivity Syllabus FallQuarter2012 Instructor JosephBerk,jhberk@csupomona.edu,9092049984 Officehoursasannouncedinclass MeetingTimesandLocation Timesasspecified,allmeetingswillbein172660 Prerequisites MinimumgradeofCorbetterinME232 Textbook MATLABforEngineers(2ndEdition)byHollyMoore,PrenticeHall CourseSummary You will utilize ME232 programming skills to develop programs that solve engineering problems. You willbeintroducedtoMATLABandOctaveandlearnusefulfunctionsthatcansolvethesameproblems. ThegeneralapproachinthiscourseislearnMATLAB/Octave,todevelopVBAprogramsforengineering problems assigned in the lab, and to use MATLAB/Octave for checking your solutions to some or all aspects of these problems. There will be very little lecture; most of the lab time will be focused on developingyourprograms.Forthisreason,youmustdoallassignedreadingsandreviewallassigned materials prior to coming to the lab. DO NOT come to the lab session without having reviewed the readingassignmentsandcoursematerialsinadvanceofourtimetogether.Therewillbenoquizzesor tests. Ourschedulewillbe: Weeks1&2 IntroductiontoMATLABandOctave,matrixalgebra,Project1assignment. Weeks3&4: Vectormath,solvingsetsoflinearequations,curvefitting,polynomialregression,interpolation, Project2assignment. Weeks5&6: Numericalintegration,calculatingareaundercurve,numericalintegrationof1storder equations,statisticalanalysis,Project3assignment. Weeks7&8: Linearinterpolation,plotting,morenumericalintegration,findingrootsofnonlinearequations, Project4assignment. Weeks9&10:

Logicalcontrolfunctions,selectionstructures,loops,readingtoandfromfiles,Project5 assignment. Obligations Yourobligationsare: Youmustpurchasethetext. You must work independently on all assignments. All material you prepare must be original. Youmaynotturninmaterialpreparedbysomeoneelseasoriginalmaterial. Youmustcompleteallassignedreadingspriortoattendingeachlabsession(withtheexception ofourfirstmeeting). Youmustcompleteallprojectassignments. Youmustnotuseyourcellphoneortextmessageduringlabsessions.Turnyoucellphonesoff priortocomingtothelab. YoumustnotsurftheInternetordoothercomputerworkunrelatedtolabassignmentsduring labassignments.Ifyoufinishearly,youshouldleave. Youmustattendalllabsessions. Youmustbeontimeforalllabsessions. Youmuststayawake. Projects Youwillberequiredtocompletefiveprojectsforthiscourse.Theseareindividualprojects(notgroup projects)andallpartsoftheproject(programcreation,obtainingresults,andprogramsubmission)must beoriginal.Theprojectsareintendedtoexposeyoutorealworldproblemsfacedbyworking engineers;theyarenotpointlesscomputationalexercises.Theywillbechallengingbothfroma programmingperspectiveandfromanengineeringperspective.Ifyouarehavingissues,usetheoffice hours,email,andthetelephonetocontactmeforassistance.Donotwaituntilshortlybeforethe projectisduetoannouncetomethatyoudontgetit. Grading Therewillbe5projects.Eachwillcountfor20%ofyourlabgrade.Youwillreceiveagradeoneach project.Thegradescaleis: 5=A 4=B 3=C 2=D <2=F YouwillearnanAinthiscoursethroughdemonstratedmaterialmasteryandprofessionalsubmittals. Thismeansyourworkmustnotcontainspellingorgrammarerrors,yourprogramsdonotcrash,your programsdelivercorrectanswers,andallworkissubmittedontime. YouwillearnaBinthiscourseisyourworkisaboveaverage,butnotexemplary.

YouwillearnnohigherthanaCinthiscourseifyourworkisaverageaspertheabovegradescale,orif oneassignmentissubmittedlate. YouwillearnnohigherthanaDinthiscourseifyourworkisbelowaverageaspertheabovegradescale oriftwoassignmentsaresubmittedlate. YouwillearnanFinthiscourseifyouarehabituallylateinarrivingforthelabsession,ifyoudonot attendalllabsessions,ifthreeormoreassignmentsarelate,orifyouraveragegradeonallassignments isbelow2.0. Anylateassignmentwillreceiveagradeof0.Anyassignmentmorethan3dayslatewillresultin coursefailure. Thebottomlinetoalloftheaboveisdonotbelateonanyassignments,donotbelateforanyofthelab sessions,turnyourcellphonesoff,andattendalllabsessions.

Student Computer Accounts

Effective Fall 2006, any engineering student taking classes may acquire a user name and password to permit use of engineering computers. Once the student has activated their account they will have access to these computers with a courtesy storage quota of 50MB. If the student is enrolled in a class the instructor may activate printing and storage privileges as required by the course. A folder will be created with the name MyEGRClassFolder on the H:drive of the student's computer. Opening the folder will give access to each of the class folders for the courses in which the students is enrolled. The student's user name for the College of Engineering computer account is the same their Cal Poly BroncoName. For the rest of the student's engineering career this user name will remain effective The password for the Engineering computer account is intially based on the student's personal information. You will be required to change the password the first time you logon. You can determine the initial password by using the following criteria: o For the first character of the password use the Upper case letter of the first letter of the first name. If the student has no first name use "X". o For the second character of the password use the Upper case letter of the of the first letter of the last name. If the student has no last name use "X". o For the third character of the password use the lower case letter of the second letter of the last name. If the student has no last name or a single letter last name use "x". o For the next four characters of the password use the 2 digit birth month and 2 digit birth date of the student's birthday. o If the first three characters in the password are the same as the students user name, add a "#" in between the first and second character of the password. o If the password still cannot be resolved contact one of the Engineering IT techs. o Examples: For an example of the above rules assume the student's name is Fred Smith, his Cal Poly e-mail username is fsmith and his birthday is June 5, 1987: His password would be FSm0605 If the student's name is Peter Ng, his Cal Poly e-mail username is png and his birthday is December 12, 1986: His password would be P#Ng1212 The student will be prompted to change the password at the first logon. The password must meet the following minimum requirements: o Not contain the user's BroncoName. o Be at least six characters in length. o Contain characters from three of the following categories: Uppercase characters ( A through Z ) Lowercase characters ( a through z ) Decimal digits ( 0 through 9 ) Non-alphabetic characters (for example, !, $, #, %)

PurposeandApproach Purpose and Approach


Continued practical Excel/VBA applications ContinuedpracticalExcel/VBAapplications
ImplementwhatyoulearnedinME232 Learn MATLAB and its capabilities LearnMATLABanditscapabilities Solvetypicalengineeringproblems U MATLAB UseMATLABasacheckonExcelVBAproblems h k E l VBA bl

Workdifferentengineeringproblemsusing Excel,VBA,andMATLAB E l VBA d MATLAB

SyllabusReview Syllabus Review


Refer to syllabus provided under separate Refertosyllabusprovidedunderseparate cover Note attendance tardiness and grading policy Noteattendance,tardiness,andgradingpolicy

CourseRequirements Course Requirements


Youmustbeontime You must be on time Youmustattendeachclass Submittalswillbeasdirectedinlab S b i l ill b di di l b YoullneedExcel,VBA,andMATLAB YoullneedOctave(freedownload)
AllareonCPPEngineeringcomputers a eo g ee g co pu e s

Workspace

MATLABIntroduction MATLAB Introduction

Command History Hi t

CommandWindow Command Window

CreatingDirectories

CreatingFiles

10

PerformingMath Operations

OperationsOrder:(),^,*,/,+, Operations Order () ^ * / + Parentheses,Exponent,MultiplicationandDivision,AdditionandSubtraction


11

ClearingCommandWindow

12

CreatingVariables

13

MATLABVariables MATLAB Variables


No need to declare variable type Noneedtodeclarevariabletype
Variablenames Must begin with letter Mustbeginwithletter Canbefollowedbycombinationsofletters, numbers,orunderscoresonly numbers or underscores only Cannotexceed63characters Are case sensitive Arecasesensitive Onceyouvedeclaredvariablesandassigned valuestothem,youcanusetheminequations values to them you can use them in equations
14

15

UseWhocommandtoseeyourvariables

16

CharacterVariables

17

MATLABFunctions MATLAB Functions


Many functions are built in to MATLAB ManyfunctionsarebuiltintoMATLAB
sin()calculatesthesine(mustbeinradians) cos() calculates the cosine (must be in radians) cos()calculatesthecosine(mustbeinradians) sqrt(x)calculatesthesquarerootofx exp(x)calculatesex ( ) l l t abs(x)calculates|x|

Chapter3outlinesseveralmorefunctions h l l f

18

ClearingVariablesFromMemory

19

FormattingHowNumbersAppear

20

Comments
In VBA we used an apostrophe InVBA,weusedanapostrophe InMATLAB,weusethe%symbol
W Wecaninsert%symbolanywhereincodeline i t% b l h i d li Alltorightignoredinprocessing

21

CreatingandSavingmfiles Creating and Saving m files


We often want to use a file previously created Weoftenwanttouseafilepreviouslycreated Wedothisbycreatingandsavingworkasan mfile m file editfilename.m filenamecanbeanyfilename

22

23

Whenyousavethefile, When you save the file youwillseethedirectory pathandthefilename

24

25

Matrices
MATLAB shines with matrix operations MATLABshineswithmatrixoperations Cancreatearrayswith
Si l l Singleelements t Rows Rowsandcolumns

Seeexamplesinfollowingcharts

26

27

Createbiggerarrayswithbrackets

28

Separaterowsofdatawithsemicolons

29

Multiplyingmatrixbyascalar

30

Recommendation:Alwaysuseperiodinfrontofoperator

Goodpracticetousemultiplication,division,orexponent operationoneachelementofarray
If we tried to square above matrix by saying c = c^2 we would get Ifwetriedtosquareabovematrixbysayingc=c 2,wewouldget errormessageduetoviolationofmatrixmultiplicationrules Ifwesquareabovematrixbysayingc=c.^2,itworks

31

Writingdataonsameline

32

Writingdataonsameline(continued)

33

Writingdataonsameline(continued)

34

ShowingNumbersandStringsOnSameRowinMatrix

Notes
You have to convert everything in matrix to a Youhavetoconverteverythinginmatrixtoa string Once youve done this, you cant perform Onceyou vedonethis,youcan tperform mathematicaloperationsdirectlyandgeta correctanswer Wecanconvertanumberthatweconverted toastringbacktoanumberusingthe str2numfunction Seenextslide

UserInputstoMATLAB User Inputs to MATLAB


Approach Createmfile Userrunsmfile fil Usermakesinputs MATLABprovidesanswer Userinputcode User input code
variableorarray=input(someinstructionsforthe userinsinglequotes) user in single quotes)
38

ExampleUserInputs

39

ReferringtoSpecificMatrixLocations

40

ChangingSpecificMatrixValues

41

OperationsUsingSpecificMatrixValues

42

PerformingOperationsonMatrices

43

PerformingOperationsonMatrices

44

PerformingFunctionsonMatrices

45

TransposingMatrices

46

ColonOperator(:) Colon Operator (:)


Used for creating matrices with step sizes Usedforcreatingmatriceswithstepsizes
a:c:b Create matrix from a to b with step size of c Creatematrixfromatobwithstepsizeofc

Usedforextractingpartsofanarray

47

CreatingMatriceswithStepSizes

48

ExtractingPortionsofArrays

49

ExtractingPortionsofArrays

50

EndCommand

51

SizeCommand

52

Numel Command

53

MatrixAlgebra Matrix Algebra


a b e f a e b f c d g h c g d h
Addition

a b e f ae bg af bh c d g h ce dg cf dh
ScalarMultiplication

Multiplication

a b wa wb w wc wd d c d
54

MatrixAddition/Subtraction

55

VectorMagnitude

56

VectorDotProducts

57

VectorCrossProducts

58

Homework
Continue Project 1 ContinueProject1 ReadChapters1through4

59

UsingMatricesToSolveLinear IndependentEquations
ME232A Weeks3and4 Weeks 3 and 4

Abitmoreonmfiles A bit more on m files


Weusemfilestocreatecode W Wecreatecodeinmfiletexteditor d i fil di Werunthemfilebytypingitsnameatthecommandline
Start m file in MATLAB by typing edit filename M file text editor opens Write text (MATLAB code)

Save file

In MATLAB, type filename

File runs

Notesonmfiles Notes on m files


Save file in default directory Savefileindefaultdirectory MATLABautomaticallyaddsthe.mextension Youhavetosaveasandaddthe.m h d dd h extensioninOctave

LinearEquations Linear Equations


Ax = B Ax=B
A=NxN array,knowncoefficients x=Nx1array,Nunknownvalues x = Nx1 array N unknown values B=Nx1array,knownconstants

S Supposewehave h
3x1 +5x2 =10 7x1 +15x2 =23

Approach
Set equations in matrix form Setequationsinmatrixform Writematrixequationasx=inv(A)*b AllowOctaveorMATLABtosolveforvariables ll O l f i bl

InMatrixForm In Matrix Form

3 5 x1 10 7 15 x 23 2

x = B

LetsUseOctave(orMATLAB)toSolve Forx1 andx2 d

Caveats
Touseprecedingapproach,equationsmustbe p g pp , q linear
Variablestofirstpower No unknowns multiplied by each other Nounknownsmultipliedbyeachother Squarematrices(onlywayyoucanhaveinverse)

Lines defined by equations are not parallel Linesdefinedbyequationsarenotparallel Canquicklydetermineifuniquesolutionexistsby findingdeterminantofcoefficientmatrix


Canonlyfinddeterminantofsquarematrix Determinantmustnot=0 If determinant = 0 unique solution does not exist Ifdeterminant=0,uniquesolutiondoesnotexist

CantTakeInverseOfMatrixwithDeterminant=0

SolvingStaticsProblemsWithMatrices
1000lb 3.2ft 75o F2 9.9ft 71o F3 7.3ft 70o F1

Verticalforces: F1 sin70o F2 sin75o F3 sin71o +1000=0 Horizontalforces: F1 cos 70o F2 cos 75o + F3 cos 71o =0 F +F 0 Moments: 20.4F sin70o 3.2F sin72 20 4 F1 sin 70o 3 2 F2 sin 72o 13 1 F3 sin 71o =0 13.1F sin71 0

Let sPutInAx B Form Lets Put In Ax =BForm


sin70o cos 70o sin75o cos 75o sin71o cos 71o F1 F2 F3 1000

=
1

0 0

20.4sin70 20 4 sin 70o 3 2 sin 72o 13 1 sin 71o 3.2sin72 13.1sin71

Systemsolutionis. System solution is.


F1 F2 F3 sin70o sin75o cos 75o sin71o cos 71o

1000 0 0

cos 70o

20.4sin70o 3.2sin72o 13.1sin71o

LetscreatethematricesinOctave

LetssolveforF1,F2,F3

Project2 Project 2
Supposeyouhaveamemberattachedtowall pp y
Wallforce D1 1 F1 D2 2 F2 D3 3 F3

WriteaMATLABprogramthatallowsusertoenter resultantverticalforceatwall,D1,D2,D3,1,2,3 Program returns F1,F2,andF3 ProgramreturnsF F and F Emailmfiletoinstructornotlaterthanspecified submittaltime NamefileyourlastnamefirstinitialP2.m

MATLABPlotting MATLAB Plotting


Weeks5&6

77

Introduction
Twodimensionalplotting Subplots Polarplots Logarithmicplots Barcharts Histograms Functionplots Threedimensionalplotting Statisticalfunctions Editingfrommenubar g Savingplots Project3 Summary y
78

TwoDimensionalPlotting Two Dimensional Plotting


Dependent and independent variables Dependentandindependentvariables UsingMATLABtocreateplots
C CanenterxydatadirectlyinMATLABastwo t d t di tl i MATLAB t matrices
X data can use step function Xdatacanusestepfunction Ydatacanbeentereddirectly

Data can be read from Excel file DatacanbereadfromExcelfile

79

SimplexyInputs

80

SimplexyInputs(continued)

81

AddingTitlesandLabels

Tosavefigures, seenextslide

82

83

ReadingDataFromExcelFile Reading Data From Excel File

84

ReadingDataFromExcel Reading Data From Excel

85

ReadingSpecificExcelData

86

AssigningSpecificExcelDatatoMatrix

87

AssigningSpecificExcelDatatoMatrix

88

AssigningSpecificExcelDatatoMatrix

89

PlottingPrecedingExcerptedExcelData

90

xandyRangescanbeinrowsorcolumns

91

Wecanexcerptdirectlyintoplotcommand

92

PlottingTrigonometricFunctions

93

PlottingTrigonometricFunctions

94

PlottingMultipleLines

95

StudyChapter5ForMoreInfoOn Study Chapter 5 For More Info On


Lineoptions Line options Coloroptions Markeroptions k i Axisoptions Legendoptions Textboxoptions Text box options

96

PolarPlots

97

PolarPlots

98

PolarPlots

99

PlottingLogarithmicFunctions Plotting Logarithmic Functions


SeeChapter5andAppendixC See C apte 5 a d ppe d C plot(x,y)
Linearplotofxandy p y

semilogx(x,y)
Logarithmicxscale,linearyscale

semilogy(x,y)
Linearxscale,logarithmicyscale

loglog(x,y)
Logarithmicxandyscale
100

BarGraphs Bar Graphs


bar(x) If i Ifxisvector,generatesaverticalbargraph;ifxisa2Dmatrix,bargroupsdata t t ti l b h if i 2D ti b d t byrow barh(x) Ifxisvector,generatesahorizontalbargraph;ifxisa2Dmatrix,groupsdata byrow bar3(x) 3Dbarchart bar3h(x) ( ) 3Dhorizontalbarchart pie(x) Piechart pie3(x) 3Dpiechart hist(x) Histogram;defaultcategorynumberis10 hist(x,a) Histogram;a=categorynumber
101

TheNormalDistribution
Assignsdatatocategories Usuallyreferredtoashistogramor frequencydistribution frequency distribution Curvecanbedescribed mathematically Distancefrommeancorrelateswith Distance from mean correlates with probabilityofoccurrence

So,howcanweusetheabove?

102

HistogramExamples

103

HistogramExamples

104

DeterminingBinSizes Determining Bin Sizes


Researchvariousapproaches esea c a ous app oac es
e.g., http://www.fmrib.ox.ac.uk/analysis/techrep/tr00mj2/ tr00mj2/node24.html t 00 j2/ d 24 ht l

Selectapproachyoufeelisappropriateandbe abletoexplainwhy able to explain why Basedonbinsizeandminandmaxdatapoints, selectnumberofcategoriesforuseinMATLAB select number of categories for use in MATLAB hist(x,a)function
Numberofcategories=(max min)/(binsize)
105

FunctionPlots
Plotsfunctionswithoutdefiningarrays

106

AnotherfplotExample

107

Three DimensionalPlots ThreeDimensional Plots


Refer to Chapter 5 RefertoChapter5

108

WeightDataCollection Weight Data Collection

109

Project3:HistogramProgram
CollectweightsofmalesinME232Alab C ll t i ht f l i ME232A l b WriteaVBAprogramthatallowsuserstoenterweightsonaform VBAprogramshouldwriteweightstoa.csvfile VBAprogramshouldreadweightsfroma.csvfile p g g VBAprogramshouldcalculateweightmeanandstandarddeviation Researchapproachesfordeterminingnormaldistributionbinsizes,select approach,haveVBAprogramdeterminebinsize VBAprogramshouldwriteweights,mean,standarddeviationtoExcelspreadsheet VBA program should write weights mean standard deviation to Excel spreadsheet MATLABprogramshouldtakeweightsandbinsizeanddisplayhistogram ProvidefollowinginWordreport: Yourname VBAcode(moduleandform) Excelspreadsheet Yourbinsize,andyourrationaleforyourbinsizeselectionapproach MATLAB code MATLABcode MATLABgeneratedhistogramwithappropriatetitleandaxislabels NameyourWorddocumentyourlastnamefirstinitialP3.docx NameyourMATLABfileyourlastnamefirstinitialP3.m NameyourExcelfileyourlastnamefirstinitialP3.xlsm Submitabovenotlaterthanspecifiedsubmittaltime
110

NumericalTechniques Numerical Techniques


Weeks7and8

Introduction
Interpolationandcurvefitting Interpolation and curve fitting Differencesandnumericaldifferentiation Numericalintegration i li i Project4 Summary

Interpolation
Linear interpolation Linearinterpolation
Assumesstraightlinebetweentwoknownpoints

Cubic spline interpolation Cubicspline


Usesthirdorderpolynomialtomodeldata

LinearInterpolation
Useinterp1function f Consider

MultipleInterpolations

PlottingMultipleInterpolations

PlottingMultipleInterpolations

CubicSpline Cubic Spline Interpolation


interp1 function defaults to linear interp1functiondefaultstolinear interpolation Linear interpolation is not always best Linearinterpolationisnotalwaysbest approach MATLAB ll MATLABallowsustospecifycubicspline if bi li interpolationtechnique
Usesthirdorderpolynomialtomodeldata Specifiedwithfourthargumentininterp1function

CubicSpline vsLinearInterpolation

CubicSplinevsLinearInterpolation

RefertoChapter12foradditionalinterp1optionsand3dimensionalinterpolation

CurveFitting Curve Fitting


MATLABhasbuiltincurvefittingfunctions g Concept
Fitaline(oracurve) y=f(x) Usingline(orcurve)equation,calculatey

MATLAB approach MATLABapproach


polyfit function polyfit(x,y,n)
x=xarray y=yarray n=polynomialexponentiationvalue p y p

LinearRegression
Bestfittingstraightline

y=2.1905x+15.9167

LinearRegression
Bestfittingstraightline

PolynomialRegression

y 0.1310x 1.2738x 15.0000 y =0.1310x2 1.2738x +15.0000

y=0.0000x3 0.1310x2 1.2738x+15.0000

NumericalDifferentiation Numerical Differentiation


If we know function, we can calculate derivative Ifweknowfunction,wecancalculatederivative Ifwehavedata(i.e.,wedontknowfunction),we canapproximatederivative pp
dy/dx =y/x=(y2y1)/(x2x1)

MATLABdifffunctionfindsdifferencesbetween vectorvalues
Canuseabovetofindslopebetweendatapairs Seenextslide

NumericalDifferentiation

NumericalIntegration Numerical Integration


MATLABcanapproximateareaundercurve ca app o ate a ea u de cu e Approach
Similartowhatwefirstlearnedincalculus Takesmallrectangularsegmentsunderunder curve Calculateareas Sumareas

Thefinerwemakesegmentsalongxaxis,the moreaccuratetheapproximationbecomes t th i ti b Letsconsiderthisfory=x2

10ysegments

Averagevaluebetweenupper andloweryineachsegment

NumericalIntegration Numerical Integration


xvector Averageyvalue A l (heightofeach segment) Approximate areaundercurve xsegments x segments Averagey value

Aboveapproximatesarea undercurve Ifwetakefinerdivisions, calculatedareabecomes calculated area becomes moreaccurate

Built InIntegrationFunctions BuiltIn Integration Functions


Builtin functions allow user to specify integral Built infunctionsallowusertospecifyintegral ofafunctionwithoutspecifyingrectangles Both accurate to within 1E 06 Bothaccuratetowithin1E06 quad
UsesadaptiveSimpsonquadrature

quadl
UsesadaptiveLobatto quadrature

quadandquadl

function (noteapostrophes)

lowerlimit

upperlimit

quadandquadl w/morecomplexfunctions quad and quadl w/more complex functions


Suppose we have a function Supposewehaveafunction y=x5 +3x4 +2x3 +1.8x2 +33.43x+12.4317 Lets
Plotabovefunction Findintegralfrom5to20

IntegratingPrecedingFunction

Project4 Project 4
Findequationdescribingnormaldistribution UsemeanandstandarddeviationfromProject3(mensweights) U d t d d d i ti f P j t3( i ht ) Plotnormaldistributionwithabovemeanandstandarddeviationusing
Excelschartingfeatures MATLABsplotfeatures

UseMATLABtofindareaundercurvefrom f d d f
1 to+1 2 to+2 3 to+3 6 t 6 6 to+6

PrepareaWorddocumentincludingExcelgraph,MATLABplot,areasundercurve, MATLABcode,explanationofeach,andwhatyoulearnedinthisassignment NameExcelfileyourlastnamefirstinitialP4.xlsx NameMATLABfileyourlastnamefirstinitialP4.m fl l f l NameWordfileyourlastnamefirstinitialP4.docx EmailabovefilestoinstructornotlaterthanmidnightonWeek8classday

Summary
Interpolationandcurvefitting Interpolation and curve fitting Differencesandnumericaldifferentiation Numericalintegration i li i Project4

LogicalFunctionsandControl Structures
ME232AWeeks9and10

Introduction
Relationalandlogicaloperators Relational and logical operators Logicalfunctions Selectionstructures S l i Loops Project5assignment Summary

MATLAB LogicalFunctionsandControlStructures i l i d l
Similar in concept to other languages Similarinconcepttootherlanguages SimilarinconcepttoVBA
S Sequentialstructure ti l t t Conditionalstructure(orselectionstructures) Repetitivestructure(loops) ( )

6MATLABRelationalOperators 6 MATLAB Relational Operators


Compare matrices of equal size Comparematricesofequalsize < lessthan <= l lessthanorequalto h l > greaterthan >= greaterthanorequalto == equal to equalto ~= notequalto

MATLABComparisons MATLAB Comparisons


Either true or false Eithertrueorfalse 1fortrue 0f f l 0forfalse

MATLABComparisons(continued) MATLAB Comparisons (continued)

MATLABLogicalFunctions MATLAB Logical Functions


find
Searchesmatrix Identifieselementsmeetingcriteria g

all
Checks to see if logical condition true for all matrix Checkstoseeiflogicalconditiontrueforallmatrix elements

any y
Checkstoseeiflogicalfunctiontrueforanymatrix elements

FindExample Find Example

AllandAnyExamples All and Any Examples

RefertoMATLABhelpformoreinformation

SelectionStructure Selection Structure


Simple if Simpleif
SimilartoIfThenElseEndIfinVBA,but Jumps to end statement Jumpstoendstatement

If/Else
SimilartoIfThenElseEndIfinVBA

SimpleIfExample Simple If Example

If/ElseExample If/Else Example

If/ElseExample(continued) If/Else Example (continued)

SeeChapter8fordiscussionofcomparisonswithmatricesversusscalars

Loops
for loop forloop
Usedwhenyouknowhowmanytimestoloop

while loop whileloop


Usedwhenaconditionmustbesatisfiedtoend loop

forLoopExample for Loop Example

forLoopExample for Loop Example

UsingforLooptoCreateMatrix Using for Loop to Create Matrix

NestingifInsideloop Nesting if Inside loop

whileLoops while Loops

UsingwhiletoCreateMatrix Using while to Create Matrix

UsingifStructureasawhile true Counter Using if Structure as a while trueCounter

Showshowmanytimesscores>90

Project5 Project 5
Anacidetchprocessremoves1%(by weight)ofanaluminumstructure i ht) f l i t t eachtimeitisdipped.Thestructure isrepeatedlydippeduntilitsweight approaches10lbs,buttheweight cannotbeallowedtodropbelow10 t b ll dt d b l 10 lbs.CreateaMATLABprogramthat allowstheusertoenterstructures weightpriortothefirstdip,andthen returns:
Howmanythetimestheproduct needstobedippedsuchthatits weightapproachesbutdoesnotdrop below10lbs. below 10 lbs Theproductsfinalweight

Workindependently Mailcompletedprogramto jhberk@csupomona.edu notlaterthan midnightnextWednesday NamefileyourfirstandlastnameP5.m N fil fi t dl t P5

157

Summary
Relationalandlogicaloperators Relational and logical operators Logicalfunctions Selectionstructures S l i Loops Project5assignment

SupplementalMaterials Supplemental Materials

159

ME232AProject1 HydraulicAccumulatorReliabilityPrediction Hydraulicaccumulatorsareusedinaircraftandotherapplicationstodampenhydraulicpressure fluctuationsandtoprovideresidualhydraulicpressureforshortperiodsifthehydraulicpressuresource (e.g.,ahydraulicpumps)failtopressurethehydrauliccircuit.Inthisregard,theyarethehydraulic systemequivalentofacapacitorinanelectricalcircuit. Thetypicalhydraulicaccumulatorisapressurized,sealedcylinder,withaslidingpiston.Pressurized hydraulicfluidisononesideofthepiston;pressurizednitrogengasisontheotherside.Ashydraulic pressurefluctuationsoccurandthepistonmovesbackandforth,thenitrogengasiscompressedor decompressedslightlytoaccountforthehydraulicpressurefluctuations. Thisistheaccumulatorengineeringassemblydrawingforthisassignment,alongwithanassociatedbill ofmaterials:

Whenfieldingordevelopingnewproducts,engineersfrequentlydevelopreliabilitypredictionsforthese products. Reliabilityisdefinedastheprobabilitythataproductwillworkwhenitissupposedtowork. Thisisusuallyexpressedasanumberbetween0and1,with0meaningtheproductwillnever work,and1meaningtheproductwillalwayswork(i.e.,itwillwork100%ofthetimeitiscalled upontodoso).

ReliabilityisalsoexpressedasMeanTimeBetweenFailures,orMTBF,whichmeanstheaverage numberofhourstheproductwillworkpriortofailing.

Engineerspreparereliabilitypredictionsbyworkingfromthepartleveluptotheassemblylevelinthe followingmanner: Eachpartisaassignedafailurerate,typicallyinfailurespermillionhours.Forexample,ifthe partshistoryisthatitfailsonceeverymillionhours,itsfailurerateis1x106.Thesefailure ratescanbefoundinpublishedsources,online,fromthecomponentsupplier,theycanbe basedonthecompanyshistorywiththepart,ortheengineermaymakeanestimateofthe failurerate.WeusuallyusetheGreekletterlambda()torepresentfailurerate.Forthis assignment,thefailureratesareprovidedtoyou. Afterfailureratesareassignedtoeachpart,thefailurerateforeachpartismultipliedbythe numberofpartsintheassemblytoprovideatotalfailurerateperpart.Inotherwords,iftwoof aparticularpartareincludedtheassemblyandthefailurerateis1x106,thetotalfailurerate forthatpartis2x106. Thefailureratesforallpartsarethensummedtoprovideatotalfailureratefortheassembly: assembly= TheassemblyMTBFissimplytheinverseoftheassemblyfailurerate: MTBFassembly=1/ Thereliabilityoftheassemblyisgivenbythefollowingequation: Reliabilityassembly=et Where e=baseofthenaturallogarithm,orapproximately2.71828183 isequaltoassembly tisequaltoassemblyoperatingtime(frequentlyreferredtoasmissiontime) Similarly,theassemblysprobabilityoffailureis1minusthereliability,or: ProbabilityofFailure=1et Heresyourassignment: CreateaVBAprogramthatallowstheusertoenter(onaformorinaninputbox)eachparts partname,partnumber,andquantityfortheaccumulatorshowninthisassignment. TheVBAprogramshouldcreateheadingsinColumnsA,B,C,D,andEofRow1inthe spreadsheetthataretitledPartName,PartNumber,Quantity,FailureRatePerEachPart,

FailureRateForAllParts(ofthesamepartnumber),andPercentageoftheTotalFailureRate (forallpartsintheassembly).TheVBAprogramshouldassignfailureratestopartsbasedon thepartnameenteredbytheuser. Usethefollowingfailurerates:


Part Cylinder Cap Separator Fitting Reducer Gasket Bearing TSeal Lockwire WarningPlate,Nameplate FailureRate(x106)PerHour 0.108 0.106 1.233 3.223 3.223 4.060 2.778 3.256 11.336 1.05

TheVBAprogramshouldtransfertheinformation,whencommandedtodoso,showingpart name,partnumber,partquantity,failurerate,andtotalfailurerateforeachpart,placingthe appropriateentryintorowsbelowtheheadingsdefinedabove.Useonerowforeachpart. TheVBAprogramshouldsumtheentriesforallofthepartfailureratestoprovideatotalfailure ratefortheaccumulatorassembly. TheVBAprogramshouldallowtheoperatortoinputanoperating(i.e.,mission)time. TheVBAprogramshouldcalculateanddisplayinthespreadsheet(withappropriatelabels),the accumulatortotalfailurerate,theaccumulatorMTBF,theaccumulatorreliability,andthe accumulatorprobabilityoffailure.Theaccumulatorreliabilityandprobabilityoffailureshould bebasedontheoperatingtimetheuserinputs. CreateaMATLABmfilethatincludesamatrixshowingthepartname,partquantity,partfailure rate,andtotalpartfailurerateforeachpartusedintheaccumulator(youshouldenterthis data,nottheuser).TheMATLABfileshouldsumthefailureratestoprovideatotalfailurerate fortheaccumulator.Assuminganoperatingtimeof2.5hours,theMATLABprogramshould displaytheaccumulatorsreliabilityandtheMTBF.ThiswillserveasacheckonyourVBA programsresults. NameyourVBAprogramyourlastnamefirstinitialP1.xslm.NameyourMATLABprogram yourlastnamefirstinitialP1.m. EmailboththeVBAandMATLABprogramstotheinstructor(jhberk@csupomona.edu)bythe assignedprojectcompletiontime.

FailurePreventionConsiderations Failure Prevention Considerations


Leaks Fatiguefailures Wearfailures Fractures Adhesivefailures Incompatiblematerialsfailures Excessclearance/interference/lubricationfailures Temperatureinducedfailures Corrosionfailures Corrosion failures Fastenerfailures Electrical/electroniccomponentfailures
160

Leaks
Historically,ADominantFailureMode... Hi i ll A D i F il M d

Mosthardwaresealedinsomemanner O rings Orings Gaskets Metaltometalseals Epoxiesandsimilarsealants Structure Valves Leakstypicallymanifestedas yp y Pressureloss Fluidloss(oildrops,etc.) Testfailuresw/leakdetectors

Let'sexamineafewcommoncauses....
161

ORingsandGaskets
CommonCausesofLeakage... g

Toomuchsqueeze Nonconforminghardware GaskOSeal Designdeficiencies Toolittlesqueeze RubberSeal ubbe Sea Nonconforminghardware f h d Designdeficiencies Interferencewithmatingparts Nicksorcuts Installationerrors p ( j gp g) Sharpsurfaces(adjoiningpartsortooling) Packagingerrors ORing Surfaceimperfections Moldingerrors Rolledortwistedsealingsurface Installationerror Improperapplication Improper application Fluidtosealincompatibilities Nobackupwhenneeded,orbackuppresentwhennot needed Contaminantsonsealingsurfaces Dryrot Backup

MetalSealFrame

ORing Squeeze O ORing g

Gasket Gasket
162

MetaltoMetalSeals
CommonCausesofLeakage Common Causes of Leakage

Metaltometalsealstypicallyusedforconduits orpressurizedlines i d li Nonconformingcomponents Eccentric(angledoroffset)connections Designdeficiencies Design deficiencies Nonconforminginstallationorcomponents Contaminantsonsealingsurfaces Overtorquing Humanerror(assemblyormaintenanceerror) Inadequateassemblyinstructions Undertorquing Humanerror(assemblyormaintenanceerror) Human error (assembly or maintenance error) Inadequateassemblyinstructions

163

EpoxiesandSimilarSealants
CommonCausesofLeakage... Common Causes of Leakage...

Impropermixratios Humanerror Inadequateassemblyinstructions I d t bl i t ti Improperenvironmentalapplication Toohot Toocold Shock/vibrationtoohigh Sh k/ ib ti t hi h Improperstorage Toohot Toocold Opencontainer(contaminants,UVexposure,air O t i ( t i t UV i exposure,etc.) Improperapplication Contaminatedsurfaces Toolittleapplied T littl li d Movementpriortocuring Incorrectepoxy/sealantspecified Expiredshelforpotlife Storagelife Storage life Applicationwindow
164

Structure
CommonCausesofLeakage Common Causes of Leakage

Porosity Processincapable Process incapable Humanerror Inadequateprocessdefinition IdealTaguchiapplication Cracks Processincapable Inadequatedesign Inadequateprocessdefinition adequate p ocess de t o Humanerror PotentialTaguchiapplication

Impactdamage

165

Valves
CommonCausesofLeakage g

Wearout Inadequatepreventivemaintenance Lifeexpectancyexceeded Life expectancy exceeded Closedtootightly Humanerrororovertorquedbymotor Inadequateoperating/maintenance/assemblyinstructions Closedtooloosely Closed too loosely Humanerrororundertorquedbymotor Inadequateoperating/maintenance/assemblyinstructions Missingcomponents Schradervalvecap h d l Contaminants Fluidcontaminated Metalorotherparticlesinducedduringvalvemanufacture Metalorotherparticlescreatedelsewhereinsystem Overpressurized Humanerror Testequipmentanomalies q p Inadequateassemblyortestinstructions
166

FatigueFailure Fatigue Failure


Fatiguefailuresinducedoraggravatedby g gg y
Repetitivestresscycling NotbeinghighenoughonSNcurve Corrosive environment Corrosiveenvironment

Compensatingprovisionsinclude
Appropriatematerial Appropriatecoatings Freedomfromcorrosiveenvironment Freedomfromsharpcorners Freedom from sharp corners StresscyclingatappropriatepointonSNcurve

167

TypicalFatigueFailure Typical Fatigue Failure

168

WearFailures Wear Failures


Can be induced by Canbeinducedby
Inappropriatematerial Inappropriatehardening pp p g Inappropriatelubrication Inappropriatemaintenanceinterval pp p Inappropriateclearances

Compensatingprovisionsinclude p gp
Addressingallabove Toleranceanalysis y
169

MechanicalInterferenceOrWear

Whatelsecanindicatemechanicalinterferenceorwear? Whatanalysiscanpredictmechanicalinterferenceorwear? What analysis can predict mechanical interference or wear?


170

Fractures
Stressedmemberscanfailasaresultof St essed e be s ca a as a esu t o
Brittlefailures Ductilefailures Stresscorrosioncracking Fatiguefailures

Compensatingprovisionsinclude
Appropriatedesignmargin A Appropriatematerialhardness i t t i lh d Freedomfromcorrosiveagentsorappropriate coatings
171

MetallurgicalEvaluations
CommonFailureCauses Common Failure Causes

Mechanicalinterferenceorwear Tensilefailures Indicatedbystretchingand"necking" Commoncauses Common causes Tensileoverload Exceedingelasticlimit Inadequatedesign Incorrectmaterial Brittlefailures Brittle failures Indicatedbysharpfracture Commoncauses Materialtoohard Incorrectheattreat Inadequatedesign I d t d i Incorrectmaterial Fatiguefailures Indicatedby"beach"marks Commoncauses Highstressandcyclicloading Inadequatedesign Incorrectmaterial Stresscorrosioncracking

172

ATypicalTensileFailure

173

TypicalBrittleFailure Typical Brittle Failure

174

StressCorrosionCracking Stress Corrosion Cracking


Induced by combination of conditions Inducedbycombinationofconditions
Corrosion Tensilestress

Stressraisers(notches,corners,etc)notrequired
Corrosioncreatesstressraisers

Stresscorrosioncrackingshouldbeconsideredif crackingoccursinnormallyductilematerial
Especiallyifcorrosioninducingconditionspresent

175

WeldFailures Weld Failures


Similartothosediscussedearlier
Overstress Corrosiveenvironment Abuse Defectivewelds
Weldschedule Contaminants(ofteninducingporosity) Wrongrodmaterial

Manyweldscontaindefectsbutdonotfail Welds fail for same reasons as other metals fail Weldsfailforsamereasonsasothermetalsfail
Stressesexceedstrength Stresscyclinginducesfatiguefailure
176

AdhesiveFailures Adhesive Failures


Canbeinducedby
Contamination Inappropriatemix Shelflifeexpiration Potlifeexpiration P t lif i ti Inappropriatestorage Bondareadimensionstoosmall/toobig Clearworkinstructions Appropriatestorage Pre mixedepoxies Premixed epoxies Appropriatecleanliness Appropriateapplication Appropriatedimensioning/tolerancing pp p g/ g
177

Compensating provisions include Compensatingprovisionsinclude

TypicalAdhesiveFailureModes Typical Adhesive Failure Modes


Whatcouldcauseanadhesivefailure? Whatcouldcauseacohesivefailure?

Cohesive C h i

Adhesive Adh i

178

Composite/AdhesiveFailures

179

IncompatibleMaterialsFailures Incompatible Materials Failures


Canbeinducedbygalvaniccorrosion yg Canbeinducedbydifferential thermalexpansion Compensatingprovisionsinclude
Appropriatecoatings Appropriatematerialsselection Appropriate materials selection Bestsource MILSTD889B,DissimilarMetals Availablefreeat A il bl f t
www.wbdg.org/ccb/FEDMIL/std889b.pdf

180

ExcessClearance/Interference/Lubrication Failures il
Usuallyinducedby
Poortolerancing/dimensioning Poormaterialselection Inadequatelubrication q

Compensatingprovisionsinclude
Appropriatetolerancing Questions
Whoassignstolerances Howdoyouassigntolerances

Appropriatematerials pp p Appropriatesurfacefinish Appropriatelubrication Appropriatemaintenanceinterval pp p


181

Temperature InducedFailures TemperatureInduced Failures


Canbecausedby y
Notrecognizingrequiredoperatingor storageenvironments Exceeding specified operating or Exceedingspecifiedoperatingor storageenvironments Inadequatedesignforrequired operatingorstorageenvironments operating or storage environments

Compensatingprovisionsinclude
Adequaterequirementsdefinition duringdesignprocess d d Appropriatedesigns

182

CorrosionFailures Corrosion Failures


Canbeinducedby y Notrecognizingrequiredoperatingorstorage environments Exceedingspecifiedoperatingorstorageenvironments di ifi d i i Inadequatedesignforrequiredoperatingorstorage environments Materialsincompatibilities Compensatingprovisionsinclude Adequaterequirementsdefinitionduringdesignprocess Appropriatedesigns

183

FastenerFailures Fastener Failures


Rivets,screws,nuts,bolts,clips,etc. Canbeinducedby
Assemblyshortfalls Inadequatedesigns Inadequate designs Inadequateassemblyinstructions Fastenerqualitydeficiencies Counterfeitfasteners

Compensatingprovisionsinclude
Appropriate torque specifications Appropriatetorquespecifications Training Appropriatedesigns
184

Electrical&ElectronicFailures Electrical & Electronic Failures


Canbeinducedby
Poorassemblytechnique Poor assembly technique Poorprocesscontrol Excessvoltage/current Inadequatetemperaturecontrol Inadequate temperature control Environment Mechanicalforces Connectionfailures Connection failures Contaminants

Compensatingprovisionsinclude
Training Processcontrol Appropriatedesigns

185

SolderJointFailures Solder Joint Failures


Threemaincauses(usuallyresultinginopencircuitsorhigh resistance)
Overloading(tensilefailure) Permanentloading(creep) Cyclic loading (fatigue) Cyclicloading(fatigue)

Sometimes
Shortcircuitsduetosolderspatter Opencircuitsduetocontaminationorothersolderdefects d h ld d f Opencircuitsduetodefectivesoldertechniques Inadequate/incorrectwavesolderingprocess Contamination Othersoldertechniqueissues

186

TypicalDefectiveSolderJoints

187

Electronic&ElectronicFailures
Disconnects Arcing Connectionsplatter Corrosion/aging Mechanicalfailures Mechanical failures

188

FailureRateConsiderations Failure Rate Considerations


uantity Failure Mode FAILURE DATA Failure Failure Mode Failure Mode Cause Rate Per Ratio (%) Million Hours 6.39442 Failure Rate Source S 1 See below

1 1

See below 0.40000 0.40000 Mechanical or corrosive damage, overtorqued. Mechanical or corrosive damage to sealing surface. Mechanical or corrosive 0.23200 NPRD-95, Pg. 2-118 g

FailureRate andFailureRateSource and Failure Rate Source


Deformed or Damaged Threads Minor internal leakage.

58.00%

D a

20.00%

0.08000

M l

Major internal leakage to

0.50%

0.00200

I l

189

FailureRate Failure Rate


Rateofoccurrenceovertime(ordistance) ( )
Not aprobability(moreonthislater)

Usuallyexpressedasfailurespermillionhours
Examples
6.23x106 1.55x106 Etc.

Mayalsobeexpressedasfailurespermillion miles
AsdoneinNPRD

OftenrepresentedbyGreekletterlambda() p y ( )
190

BathtubCurve Bathtub Curve

191

DFMEABathtubCurveAssumptions DFMEA Bathtub Curve Assumptions


Weareinthetub Infantmortalitynotafactor
Inspection Prescreening Processcontrolsatcomponentmanufacturer

Wearout not a factor Wearoutnotafactor


Preventivemaintenance Infinitelifedesign

Weshouldconsiderfailureeffects
Butassignratesbasedonabove
192

FailureRates,Probability,andReliability Failure Rates, Probability, and Reliability


Failurerate
Occurrences/Time / Occurrences/Distance

Probability
Likelihoodsomethingwilloccur
0<P<1.0 0<P<100%

Reliability
Probability part/subassembly/system performs intended function Probabilitypart/subassembly/systemperformsintendedfunction whencalledupontodoso
0<R<1.0 0<R<100%

Reliability=et Probabilityoffailure=1 et

193

MeanTimeBetweenFailures Mean Time Between Failures


Meantimebetweenfailures(MTBF) Mean time between failures (MTBF) Meancyclesbetweenfailures(MCBF) Meanmilesbetweenfailures(MMBF) il b f il ( ) MTBF=1/ =1/MTBF

194

FailureRateSources Failure Rate Sources

195

FailureRateSources Failure Rate Sources


Observation
Electronicdatabasesmuchmoredevelopedthanmechanicaldatabases p

MILHDBK217F
Primarysourceforelectronicsfailureratedata Excellentinformationonsomemechanicaldevices Voluminous Free(www.sre.org/pubs/MilHdbk217F.pdf)

NonelectronicPartsReliabilityData 2011
Availableforpurchasefromhttp://theriac.org/ Premiersourcefornonelectronicdata

USNavyMechRelsoftware
Free(http://www.navsea.navy.mil/nswc/carderock/pub/mechrel/products/software.aspx) Modifiesfailureratesforenvironments

Google g Companyspecificfailureratedatabase
Yourorganization Yoursuppliers

Component/subassemblymanufacturers p / y
196

TypicalMIL HDBK 217Data Typical MILHDBK217 Data

197

TypicalMILHDBK217Data(continued)

198

TypicalNPRDData Typical NPRD Data

199

MoreonFailureRates More on Failure Rates


Datamaybedirectlyavailableonstandardcomponents Data will not be directly available on components specific to Datawillnotbedirectlyavailableoncomponentsspecificto yourdesigns
Machined/casthousings Shafts Etc.

Recommendedapproach
Use your database (if you have one) Useyourdatabase(ifyouhaveone) or Selectsimilarcomponentsfrompublishedsources
Usefailureratesforsimilarcomponents

Makeobjective/reasonable adjustmentsbasedon
Designmargin/loads Loadstandarddeviationversusstrength Application pp Otherfactors
200

AWordOn
AndWhereWereGoingWithIt

Considerable subjectivity here Considerablesubjectivityhere Weregoingtousefailureratesfor


F il FailureModeEffectSummary(FMES) M d Eff t S (FMES) Reliabilitypredictions Identifyinghighprobability,highriskareas

201

FailureRateModifiers Failure Rate Modifiers


Concept
Failurerateincreasesordecreasesasaresultof environment
Operatingstress Componentqualitylevel Temperature T t Cyclingrate q p yp Otherfactorsuniquetocomponenttype

Weuseabovetoadjustfailurerateupor down
202

HumanErrorProbabilities Human Error Probabilities


Bottom line: Its not zero Bottomline:It snotzero Oneofthebestreferences
htt // http://panko.shidler.hawaii.edu/HumanErr/ k hidl h ii d /H E /

Suggestedrange:0.5to102 (50%to1%)

203

DormantFailureRates Dormant Failure Rates


Scienceisinexact Sc e ce s e act Especiallyformechanicalparts Bestsourceofinformationisproduct specific Best source of information is productspecific experience Dormantfailureratedrivers
Temperature TheArrheniusrelationship Temperaturecycling Humidity(corrosion)
204

OtherDormantFailureRateModifiers Other Dormant Failure Rate Modifiers


MILHDBK217B MIL HDBK 217B NavyMechRelprogram

205

AssessingLong TermStorageFailureRates Assessing LongTerm Storage Failure Rates


Acceleratedagingtesting cce e ated ag g test g Productspecificexperience Known Warrantydata Repairdata Repair data Part/subassemblyorderingdata
Caution required here Cautionrequiredhere
Swaptilyadroprepairapproach

Specificresearchtoquantifylongtermeffects
206

You might also like