matlab examples - flow control and loops · flow control and loops in matlab flow control: •...

26
MATLAB Examples Hans-Petter Halvorsen, M.Sc. Flow Control and Loops

Upload: others

Post on 28-May-2020

37 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

MATLABExamples

Hans-PetterHalvorsen,M.Sc.

FlowControlandLoops

Page 2: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

FlowControlandLoopsinMATLABFlowControl:• if-elseif-else statement• switch-case-otherwisestatementLoops:• for Loop• while Loop

Thebehavioristhesameasinotherprogramminglanguages.ItisassumedyouknowaboutForLoops,WhileLoops,If-ElseandSwitchstatementsfromotherprogramminglanguages,sowewillbrieflyshowthesyntaxusedinMATLABandgothroughsomesimpleexamples.

Page 3: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •
Page 4: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

If-elseStatementsGiventhesecondorderalgebraicequation:

𝑎𝑥# + 𝑏𝑥 + 𝑐 = 0Thesolution(roots)isasfollows:

𝑥 =

−𝑏 ± 𝑏# − 4𝑎𝑐�

2𝑎 , 𝑎 ≠ 0

−𝑐𝑏 , 𝑎 = 0, 𝑏 ≠ 0

∅, 𝑎 = 0, 𝑏 = 0, 𝑐 ≠ 0ℂ, 𝑎 = 0, 𝑏 = 0, 𝑐 = 0

where∅- thereisnosolution,ℂ - anycomplexnumberisasolution

Page 5: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

If-elseStatements

Createafunctionthatfindsthesolutionforxbasedondifferentinputvaluesfor𝑎,𝑏 and𝑐,e.g.,

function x = solveeq(a,b,c)

Wewilldothefollowing:• Useif-elsestatementstosolvetheproblem• TestthefunctionfromtheCommandwindowtomakesureitworksasexpected,e.g.,

>> a=0, b=2,c=1>> solveeq(a,b,c)

Page 6: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

function x = solveeq(a,b,c)if a~=0

x = zeros(2,1);x(1,1)=(-b+sqrt(b^2-

4*a*c))/(2*a);x(2,1)=(-b-sqrt(b^2-

4*a*c))/(2*a);elseif b~=0

x=-c/b;elseif c~=0

disp('No solution') else

disp('Any complex number is a solution') end

Youmaydefinethefunctionlikethis:

Page 7: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

>> a=0, b=2,c=1a =

0b =

2c =

1>> solveeq(a,b,c)ans =

-0.5000

Wetestthefunction:>> a=1;, b=2;,c=1;>> solveeq(a,b,c)ans =

-10

>> a=0;, b=0;,c=1;>> solveeq(a,b,c)No solution

>> a=0;, b=0;,c=0;>> solveeq(a,b,c)Any complex number is a solution

>> a=1;, b=1;, c=2;>> solveeq(a,b,c)

ans = -0.5000 + 1.3229i -0.5000 - 1.3229i

1

23

Page 8: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •
Page 9: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

Switch-CaseStatements• CreateafunctionthatfindseithertheAreaorthecircumferenceofacircleusingaSwitch-Casestatement

𝐴 = 𝜋𝑟#𝑂 = 2𝜋𝑟

• Youcan,e.g.,callthefunctionlikethis:

>> r=2;>> calc_circle(r,1) % 1 means area>> calc_circle(r,2) % 2 means circumference

Page 10: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

function result = calc_circle(r,x)

switch xcase 1

result=pi*r*r;case 2

result=2*pi*r;otherwise

disp('only 1 or 2 is legal values for x')end

Wecandefinethefunctionlikethis:

Testingthefunction:>> r=5;, calc_circle(r,1)ans =

78.5398>> r=5;, calc_circle(r,2)ans =

31.4159

>> r=5;, calc_circle(r,3)only 1 or 2 is legal values for x

Usinganillegalvaluegives:

Page 11: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •
Page 12: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

FibonacciNumbers

• Inmathematics,Fibonaccinumbersarethenumbersinthefollowingsequence:

0,1,1,2,3,5,8,13,21,34,55,89,144,…• Bydefinition,thefirsttwoFibonaccinumbersare0and1,andeachsubsequentnumberisthesumoftheprevioustwo.Somesourcesomittheinitial0,insteadbeginningthesequencewithtwo1s.

• Inmathematicalterms,thesequence𝑓8 ofFibonaccinumbersisdefinedbytherelation:

𝑓8 = 𝑓89: + 𝑓89#• withseedvalues:

𝑓; = 0, 𝑓: = 1

ForLoops

Page 13: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

FibonacciNumbers

WewillwriteafunctioninMATLABthatcalculatestheNfirstFibonaccinumbers,e.g.,

ForLoops

>> fibonacci(N)ans =

0112358

132134

WewillseaForlooptosolvetheproblem.

Page 14: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

function f = fibonacci(N)

f=zeros(N,1);f(1)=0;f(2)=1;

for k=3:Nf(k)=f(k-1)+f(k-2);

end

>> fibonacci(N)ans =

0112358132134

WedefinetheFunction:

Weexecutethefunction:

Page 15: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •
Page 16: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

WhileLoops

• CreateaScriptorFunctionthatcreatesFibonacciNumbersuptoagivennumber,e.g.,

>> maxnumber = 2000;>> fibonacci(maxnumber)

Page 17: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

function f = fibonacci2(max)f(1)=0;f(2)=1;

k=3;while f < max

f(k)=f(k-1)+f(k-2); k=k+1;

end>> maxnumber=200; fibonacci2(maxnumber)

ans =0 1 1 2 3 5 8

13 21 34 55 89 144 233

Thefunctioncanbewrittenlikethis:

Testingthefunctiongives:

Page 18: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •
Page 19: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

ForLoops

• Extendyourcalc_average functionfromapreviousexamplesoitcancalculatetheaverageofavectorwithrandomelements.UseaForlooptoiteratethroughthevaluesinthevectorandfindsumineachiteration:

mysum = mysum + x(i);

• TestthefunctionintheCommandwindow

Page 20: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

>> z=calc_average(x,y)z =

3

WetestthefunctionintheCommandwindow

PreviousVersionofcalc_average function:

Page 21: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

function av = calc_average2(x)

mysum=0;N=length(x);

for k=1:N mysum = mysum + x(k);

end

av = mysum/N;

>> x=1:5x =

1 2 3 4 5>> calc_average2(x)ans =

3

Thefunctioncanbewrittenlikethis:

Testingthefunctiongives:

Page 22: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •
Page 23: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

If-elseStatement

Createafunctionwhereyouusethe“if-else”statementtofindelementslargerthenaspecificvalueinthetaskabove.Ifthisisthecase,discardthesevaluesfromthecalculatedaverage.Examplediscardingnumberslargerthan10gives:

x =4 6 12

>> calc_average3(x)ans =

5

Page 24: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

function av = calc_average2(x)

mysum=0;total=0;N=length(x);

for k=1:N

if x(k) < 10mysum = mysum + x(k);total=total+1;

end

end

av = mysum/total;

Thefunctioncanbewrittenlikethis:

Testingthefunctiongives:

x =4 6 12

>> calc_average3(x)ans =

5

Page 25: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •
Page 26: MATLAB Examples - Flow Control and Loops · Flow Control and Loops in MATLAB Flow Control: • if-elseif-else statement • switch-case-otherwise statement Loops: • for Loop •

Hans-PetterHalvorsen,M.Sc.

UniversityCollegeofSoutheastNorwaywww.usn.no

E-mail:[email protected]:http://home.hit.no/~hansha/