Sie sind auf Seite 1von 13

LogicalFunctionsandSelectionConstructsinMATLAB

Ref.Moorech.8,Palmch.4
Inthispartoftheclassweintroducekeyconceptsinprogramdesign
anddevelopment.
Relationaloperators

==,<,<=,>,>=

Revisitrepetitionloops

for,while

Logicaloperators

~,&,&&,|and||

Programdesignanddevelopment
Sequentialoperations
Executionofinstructionsinorder(toptobottomofsequence)

Conditionaloperations
Executionofinstructionsiscompleteddependingonananswertoa
conditionalquestion.Theanswercouldbeyesorno.

Iterativeoperations
Thesearealsocalledloops.Theyrepeatablockofinstructions
1|P a g e

Implementkeyprogrammingstrategies

Initialization
Convergence
Forandwhileloops
Emphasisonmfunctionfilesyntax

2|P a g e

Flowcontrol
Ref.Palmsection4.4
Repetitionloops,forandwhile

Asequenceofcalculationsisrepeateduntileither
1.Allelementsinavectorormatrixhavebeenprocessed
or

2.Thecalculationshaveproducedaresultthatmeetsa
predeterminedterminationcriterion

Loopingisachievedwithforloopsandwhileloops.

Thebasicforendconstruct

fori=j:k
statement
statement
%comment
action(e.g.plot)
end

Anothervalidsyntaxformis

fori=j:m:k
statements
end

iisanindex,avariable,jandkarethestartandendpointsrespectively
ofthefor(repetition)construct,andmistheincrementation

3|P a g e

Typicalstructureofaforloopforaccumulationordepletion
x=1:5;

%createarowvector1,2,3,4,5
%initializethevariablesumx
sumx=0;

fork=1:length(x)
sumx=sumx+x(k) %Noteuseasubscriptingausefulconceptforlater
end

Runningthisscriptwouldechothevaluesofsumxinthecommand
window:

sumx=
1
sumx=
3
sumx=
6
sumx=
10
sumx=
15

Questions.

1. Doestheinitialvalueforsumxneedtobelimitedto0
2. Doestheincrementationneedtobelimitedto1
3. Doesthenumberofarithmeticoperationshavetobelimitedto2

4|P a g e

Typicalstructureofawhileendloopforaccumulationordepletion

x=0;
%setthebeginningofthevectorforsummation
sumx=0; %initializethevariablethatwillaccumulatearrayentries
whilex<6 %settheterminationpointas1pastthelimit
sumx=sumx+x %accumulationpoint
x=x+1;

%updatethearray
end

Runningthescriptaboveechoesthefollowinginthecommandwindow

sumx=
0
sumx=
1
sumx=
3
sumx=
6
sumx=
10
sumx=
15

Usewhileloopswithgreatcautionbecauseoftheirassociatedriskof
triggeringendlessloops

Wewillexplorewhileloopsasefficientconvergencecontroltoolsin
recursiveoriterativesequenceinnumericalmethods

5|P a g e


ComputingsquarerootswithNewtonsiterativemethod

Hereisthebasicstructureforestimatingthesquarerootof2,ref.Hahn

1. Initializea
2. Initializextoa/2
3. Repeat6times(say)
Replacexby(x+a/x)/2
Displayx
4. Stop

Generateanmfunctionfileforaccomplishingthisalgorithm

functionNewtonSqrt(a)
%Sampleprogrammingfordeterminingsquarerootinarepetitionstructure
%uselongformattoseeconvergencetrendsmoreeasily
%
%Synopsis:CallthefunctionNewtonSqrtandpassanumericalvalue'a'
%whosesquarerootweneedtoapproximate

formatlong
x=a/2;
disp(['Theapproachtosqrt(a)fora=',num2str(a)]);
fori=1:6
x=(x+a/x)/2;
disp(x)
end
disp('Matlab''svalue:')
disp(sqrt(a))

Advice
Startwithabasiccodeshellandcreateanerrorfreeself
containedfunctionfile.
Graduallyaddfunctionalityandautomationtoproducean
efficientfunctionfilewithinputsandoutputsaswarranted.
6|P a g e

Decisionmaking

Itisoftennecessarytocompletecertaincomputationsequences
onlywhenspecificconditionsregardingthedataorcomputed
quantitiesaresatisfied.

Suchdecisionsareachievedwiththeaidofrelationaloperators
showninTable8.1p.272Moore

Familiarizewiththeeffectofassigninglogicaloperatorstoavariable

Whatwouldyouexpecttobetheoutcomeof:

x=3>2%xisalogical(1or0)correspondingtothestatement3>2
x=2~=2%xisalogical(1or0)correspondingtothestatement2~=2

Usinglogicaloperatorswitharrays:
>>x=2:4
x=
2101234
>>y=2*x+2
y=
6420246
>>x<y
ans=
1110000

Experimentwithcasesinvolving<=,>=,~=and==

7|P a g e

Useofthefindfunction

Thefindfunctionisusedtosearchandidentifythelocation(counter)
ofvariablesbasedonlogicaloperators.E.g.Inagroupofseven
studentswhoserecordedheightsare62,67,65,72,69,61,5878and
75inchesidentifystudentswhoseheightislessthanorequalto66
inches.

>>height=[62,67,65,72,69,61,58,78,75]
height=
626765726961587875
>>accept=find(height<=66)
accept=
1367

Theacceptarrayispointeroftheentriesofheightacceptabletothe
findexercise.Thatis,intheorderofappearance,students1,36
and7areacceptable.

Nowidentifythecorrespondingheightsoftheacceptcategory

>>height(accept)
ans=
62656158

8|P a g e

Thebasicifendconstruct

ifconditionstatement
executablestatement..
executablestatement
end

Conditionisalogicalexpressioni.e.itcontainsarelationaloperator
whichiseithertrueoffalse.

Ifconditionistruethenexecutablestatementsareexecuted

Ifconditionisfalsenothinghappensinthepertinentpartofthe
code,i.e.MATLABskipstothematchingendstatement,(incaseof
multipleifendconstructs

Conditionalstatementscanbeusedindividuallyorconjugated.We
willuseillustrations

ImplementationoftheSimpleifendconstruct

Pseudocode:Givenascalarvariablex,computexonlyifx0
MATLABcode:

%simplescripttoexperimentwiththesimpleifendconstruct
x=input('enteravalueforx');
ifx>=0
y=sqrt(x)
end

Byexperimentingwiththisscript,youshouldgetanoutputforyfor
inputsofxthatarepositive,andNOoutputwhenxis0ornegative.
9|P a g e

Nestedifendconstructs
Pseudocode:Giventwoscalarvariablesxandy,computenewvariables
z=x+yandw=lnx3logywhenbothxandyare0.

MATLABcodeoption1

%simplescripttoexperimentwithcompoundifendconstructs
x=input('enteravalueforx');
y=input('enteravaluefory');
ifx>=0
ify>=0
z=sqrt(x)+sqrt(y)
w=log(x)3*log(y)
end
end
Thisscripthastheflexibilitytoproducenooutputoroneoutputortwo
outputs.

Considerthenextoption
MATLABoption2
%simplescripttoexperimentwithcompoundifendconstructs
x=input('enteravalueforx');
y=input('enteravaluefory');
if(x>=0)&&(y>=0)
z=sqrt(x)+sqrt(y)
w=log(x)3*log10(y)
end

Thisscriptismorerestrictive.Outputispossibleonlyifboth
conditionalstatementsaresatisfied.

10|P a g e

Theifelseendconstruct

Tointroducemorecomputationalflexibilityasaresultofaconditional
statement,elsestatementcomesinhandy.Simplelayoutisasfollows:
ifconditionalstatement
statementsgroupA
else
statementsgroupB
end
Pseudocode:Givenascalarvariablexcomputeanewy=xwhen0
y=ex1whenx<0

MATLABcode:

%theifelseendconstruct
x=input('enteravalueforx');
ifx>=0
y=sqrt(x)
else
y=exp(x)1
end
Runningthecodeproducesoneoutcomeforybasedontheinput

enteravalueforx:2
y=
1.4142
enteravalueforx:1
y=
1.7183

Moreflexibilityinselectionasnecessarywithotherconstructs:
11|P a g e


Theelseifstatementoptions
%theelseifconstructoptions
iflogicalexpression1
statementgroupA
elseiflogicalstatement2
statementsgroupB
else
statementgroup3
end

Noticethattheelsestatementcomesaftertheelseifstatement
Noticealsothatwehaveasingleclosingendstatementlargelybecause
wehaveoneifstatement.

%theelseifconstructoptions
x=input('enteravalueforx:');
ifx>10;
y1=log(x)
elseifx>=0
y2=sqrt(x)
else
y3=exp(x)1
end

Notecarefullythereisanoverlapofvaluesthatsatisfyboththex>0
andx>=0conditions.Oncethefirstconditionissatisfied,theother
conditionswillbeskipped.Thusvaluesof0<=x<9willtriggerthe
computationofy1.Thereisnoambiguitywithvalueofx>10,orx<0

12|P a g e

Runningthisscriptwithx=10,x=11andx=1resultsinthefollowing
outputs.
enteravalueforx:10
y2=
3.1623
enteravalueforx:11
y1=
2.3979
enteravalueforx:1
y3=
1.7183

Trythefollowingscenarios:
1. Explorethesurprisingoutcomeoftheif_elseif_elsecodeabove
whenthe10witha0andthe0witha10

2. Ifwesplittheelsifintoelseif,thenwewouldneedtwoclosing
endstatements,sincebydoingsoweintroduceanextraif
statementwhichwouldrequireitsownclosingendstatement.Try
itforyourselfbymodifyingthecodeaboveinMATLAB.You
shouldgetthesameresults.

13|P a g e

Das könnte Ihnen auch gefallen