matlab solutions - part 1 - telemark university collegehome.hit.no/~hansha/documents/lab/lab...

52
University College of Southeast Norway MATLAB Part I: Introduction to MATLAB Hans-Petter Halvorsen, 2016.06.22 http://home.hit.no/~hansha

Upload: duongque

Post on 09-Mar-2018

251 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

UniversityCollegeofSoutheastNorway

MATLAB PartI:IntroductiontoMATLAB

Hans-PetterHalvorsen,2016.06.22

http://home.hit.no/~hansha

Page 2: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

MATLABCourse,PartI-Solutions

TableofContents1 Introduction......................................................................................................................4

2 TheMATLABEnvironment................................................................................................5

3 UsingtheHelpSysteminMATLAB....................................................................................6

4 MATLABBasics..................................................................................................................7

Task1: BasicOperations............................................................................................7

Task2: Statisticsfunctions.........................................................................................7

Task3: VectorsandMatrices.....................................................................................8

5 LinearAlgebra;VectorsandMatrices...............................................................................9

Task4: Matrixmanipulation......................................................................................9

Task5: LinearEquations..........................................................................................10

6 MFiles;ScriptsandUser-definedfunctions....................................................................12

Task6: Script............................................................................................................12

Task7: User-definedfunction.................................................................................13

Task8: User-definedfunction.................................................................................13

7 Plotting............................................................................................................................15

Task9: Plotting........................................................................................................15

Task10: Plotofdynamicsystem...........................................................................15

Task11: Sub-plots..................................................................................................17

Task12: OtherPlots...............................................................................................18

8 FlowControl....................................................................................................................21

Task13: If-elseStatements....................................................................................21

Task14: Switch-CaseStatements..........................................................................22

Task15: FibonacciNumbers..................................................................................23

Page 3: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

MATLABCourse,PartI-Solutions

Task16: WhileLoop...............................................................................................24

Task17: ForLoops.................................................................................................25

Task18: If-elseStatement.....................................................................................26

9 Mathematics...................................................................................................................28

Task19: BasicMathfunction.................................................................................28

Task20: Statistics...................................................................................................28

Task21: Conversion...............................................................................................29

Task22: Trigonometricfunctionsonrighttriangle...............................................30

Task23: Lawofcosines..........................................................................................31

Task24: Plotting....................................................................................................32

Task25: Complexnumbers....................................................................................33

Task26: Complexnumbers....................................................................................35

Task27: Polynomials.............................................................................................37

Task28: Polynomials.............................................................................................38

Task29: PolynomialFitting....................................................................................39

10 AdditionalTasks..........................................................................................................41

Task30: User-definedfunction..............................................................................41

Task31: MATLABScript.........................................................................................42

Task32: Cylindersurfacearea...............................................................................44

Task33: CreateadvancedexpressionsinMATLAB................................................46

Task34: SolvingEquations.....................................................................................47

Task35: Preallocatingofvariablesandvectorization............................................48

Task36: NestedForLoops.....................................................................................49

Page 4: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

4

1 IntroductionTherearenotasksforthischapter

Page 5: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

5

2 TheMATLABEnvironmentTherearenotasksforthischapter.

Page 6: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

6

3 UsingtheHelpSysteminMATLAB

Therearenotasksforthischapter.

Page 7: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

7

4 MATLABBasicsTask1: BasicOperations

TypethefollowingintheCommandwindow:

>>y=16; >>z=3; >>y+z

Note!Whenyouuseasemicolon,nooutputwillbedisplayed.Trythecodeabovewithandwithoutsemicolon.

Note!Somefunctionsdisplayoutputevenifyouusesemicolon,likedisp,plot,etc.

Otherbasicoperationsare:

>>16-3 >>16/3 >>16*3

→Trythem.

[EndofTask]

Solution:

Nosolutionneeded.

Task2: Statisticsfunctions

Createarandomvectorwith100randomnumbersbetween0and100.Findtheminimumvalue,themaximumvalue,themeanandthestandarddeviation.

[EndofTask]

Solution:

Weusetherandfunctionwhichcreatesanumberbetween0and1.

Page 8: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

8 MATLABBasics

MATLABCourse,PartI-Solutions

x=rand(100,1)*100; min(x) max(x) mean(x) std(x)

Task3: VectorsandMatrices

TypethefollowingvectorintheCommandwindow:

𝑥 =123

TypethefollowingmatrixintheCommandwindow:

𝐴 = 0 1−2 −3

TypethefollowingmatrixintheCommandwindow:

𝐶 =−1 2 04 10 −21 0 6

→UseMATLABtofindthevalueinthesecondrowandthethirdcolumnofmatrixC.

→UseMATLABtofindthesecondrowofmatrixC.

→UseMATLABtofindthethirdcolumnofmatrixC.

[EndofTask]

Solution:

Code:

x=[1;2;3] A=[0 1; -2 -3] C=[-1 2 0; 4 10 -2; 1 0 6] C(2,3) C(2,:) C(:,3)

Page 9: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

9

5 LinearAlgebra;VectorsandMatrices

Task4: Matrixmanipulation

GiventhematrixA,BandC:

𝐴 = 0 1−2 −3 , 𝐵 = 1 0

3 −2 , 𝐶 = 1 −1−2 2

→SolvethefollowingbasicmatrixoperationsusingMATLAB:

• 𝐴 + 𝐵• 𝐴 − 𝐵• 𝐴/ • 𝐴01• 𝑑𝑖𝑎𝑔 𝐴 , 𝑑𝑖𝑎𝑔(𝐵)• 𝑑𝑒𝑡 𝐴 , 𝑑𝑒𝑡(𝐵)• 𝑑𝑒𝑡 𝐴𝐵 • 𝑒𝑖𝑔 𝐴

whereeig=Eigenvalues,diag=Diagonal,det=Determinant

→UseMATLABtoprovethefollowing:

• 𝐴𝐵 ≠ 𝐵𝐴• 𝐴 𝐵𝐶 = 𝐴𝐵 𝐶• 𝐴 + 𝐵 𝐶 = 𝐴𝐶 + 𝐵𝐶• 𝐶 𝐴 + 𝐵 = 𝐶𝐴 + 𝐶𝐵• det 𝐴𝐵 = det 𝐴 det 𝐵 • det 𝐴/ = det(𝐴)• 𝐴𝐴01 = 𝐴01𝐴 = 𝐼

where 𝐼 istheunitmatrix

[EndofTask]

Solution:

Page 10: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

10 LinearAlgebra;VectorsandMatrices

MATLABCourse,PartI-Solutions

Code:

% Define matrices A=[0 1; -2 -3] B=[1 0; 3 -2] C=[1 -1; -2 2] %Solving: A+B A-B A' inv(A) diag(A), diag (B) det(A), det(B) det(A*B) eig(A) %Proving: A*B,B*A A*(B*C),(A*B)*C (A+B)*C, A*C + B*C C*(A+B), C*A + C*B det(A*B), det(A)*det(B) det(A'), det(A) A*inv(A), inv(A)*A

Task5: LinearEquations

Giventheequations:

𝑥1 + 2𝑥@ = 53𝑥1 + 4𝑥@ = 6

Settheequationsonthefollowingform:

𝐴𝑥 = 𝑏

→FindAandb.

Solvetheequations,i.e.,find 𝑥1,𝑥@,usingMATLAB.

𝐴𝑥 = 𝑏 → 𝑥 = 𝐴01𝑏

[EndofTask]

Solution:

Weget:

Page 11: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

11 LinearAlgebra;VectorsandMatrices

MATLABCourse,PartI-Solutions

1 23 4D

𝑥1𝑥@ = 5

6E

MATLABCode:

A=[1 2; 3 4] b=[5;6] x=inv(A)*b

Theanswerbecomes:

𝑥1 = −4, 𝑥@ = 4.5

Page 12: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

12

6 MFiles;ScriptsandUser-definedfunctions

Task6: Script

CreateaScript(M-file)whereyoucreateavectorwithrandomdataandfindtheaverageandthestandarddeviation

RuntheScriptfromtheCommandwindow.

[EndofTask]

Solution:

Script:

RunningtheScriptfromtheCommandwindow:

Page 13: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

13 MFiles;ScriptsandUser-definedfunctions

MATLABCourse,PartI-Solutions

Task7: User-definedfunction

Createafunctioncalc_averagethatfindstheaverageoftwonumbers.

Testthefunctionafterwardsasfollows:

>>x=2; >>y=4; >>z=calc_average(x,y)

[EndofTask]

Solution:

Thefunctionmaybedefinedas:

Runningthefunction:

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

Task8: User-definedfunction

Createafunctioncirclethatfindstheareainacirclebasedontheinputparameterr(radius).

RunandtestthefunctionintheCommandwindow.

[EndofTask]

Solution:

Thefunction:

function A = circle(r)

Page 14: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

14 MFiles;ScriptsandUser-definedfunctions

MATLABCourse,PartI-Solutions

A=pi*r*r;

TestingthefunctionfromtheCommandwindow:

>> circle(1) ans = 3.1416 >> circle(2) ans = 12.5664

Or:

>> r=4; >> A=circle(r) A = 50.2655

Page 15: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

15

7 PlottingTask9: Plotting

IntheCommandwindowinMATLABwindowinputthetimefromt=0secondstot=10secondsinincrementsof0.1secondsasfollows:

>>t=[0:0.1:10];

Then,computetheoutputyasfollows:

>>y=cos(t);

UsethePlotcommand:

>>plot(t,y)

[EndofTask]

Solution

Nosolutionneeded.

Task10: Plotofdynamicsystem

Giventheautonomoussystem:

𝑥 = 𝑎𝑥

where 𝑎 = − 1/ ,where 𝑇 isthetimeconstant

Thesolutionforthedifferentialequationis:

𝑥 𝑡 = 𝑒HI𝑥J

Set 𝑇 = 5andtheinitialcondition 𝑥(0) = 1

→CreateaScriptinMATLAB(.mfile)whereyouplotthesolution 𝑥(𝑡) inthetimeinterval0 ≤ 𝑡 ≤ 25

→AddGrid,andproperTitleandAxisLabelstotheplot.

Page 16: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

16 Plotting

MATLABCourse,PartI-Solutions

[EndofTask]

Solution:

Wedefineascript(m-file):

Theresultbecomes:

Page 17: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

17 Plotting

MATLABCourse,PartI-Solutions

Task11: Sub-plots

PlotSin(x)andCos(x)in2differentsubplots.

AddTitlesandLabels.

[EndofTask]

Solution:

Wedefineascript:

% Define x-values x=0:0.01:2*pi; % subplot 1 subplot(2,1,1) plot(x, sin(x)) title('Plotting sin(x)') xlabel('x') ylabel('sin(x)') % Subplot 2 subplot(2,1,2) plot(x, cos(x)) title('Plotting cos(x)') xlabel('x') ylabel('cos(x)')

Runningthescriptgivesthefollowingplot:

Page 18: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

18 Plotting

MATLABCourse,PartI-Solutions

Task12: OtherPlots

Checkoutthehelpforthefollowing2DfunctionsinMATLAB:loglog,semilogx,semilogy,plotyy,polar,fplot,fill,area,bar,barh,hist,pie,errorbar,scatter.

→Trysomeofthem,e.g.,bar,histandpie.

[EndofTask]

Solution:

Wecreateabarplotusingthebarfunction:

>> x=rand(10,1) x = 0.6557 0.0357 0.8491 0.9340 0.6787 0.7577 0.7431 0.3922 0.6555 0.1712

Page 19: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

19 Plotting

MATLABCourse,PartI-Solutions

>> bar(x)

Thisgivesthefollowingplot:

Usingthehistfunctiongives:

>> hist(x)

Usingthepiefunctiongives:

Page 20: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

20 Plotting

MATLABCourse,PartI-Solutions

>> pie(x)

Page 21: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

21

8 FlowControlTask13: If-elseStatements

Giventhesecondorderalgebraicequation:

𝑎𝑥@ + 𝑏𝑥 + 𝑐 = 0

Thesolution(roots)isasfollows:

𝑥 =

−𝑏 ± 𝑏@ − 4𝑎𝑐2𝑎 , 𝑎 ≠ 0

−𝑐𝑏 , 𝑎 = 0, 𝑏 ≠ 0

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

where ∅-thereisnosolution, ℂ -anycomplexnumberisasolution

→Createafunctionthatfindsthesolutionforxbasedondifferentinputvaluesfora,bandc,e.g.,

function x = solveeq(a,b,c) …

→Useif-elsestatementstosolvetheproblems

→TestthefunctionfromtheCommandwindowtomakesureitworksasexpected,e.g.,

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

[EndofTask]

Solution:

Youmaydefinethefunctionlikethis:

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);

Page 22: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

22 FlowControl

MATLABCourse,PartI-Solutions

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

Wetestthefunction:

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

Or:

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

Or:

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

Or:

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

Task14: Switch-CaseStatements

CreateafunctionthatfindseithertheAreaorthecircumferenceofacircleusingaSwitch-Casestatement

Youcan,e.g.,callthefunctionlikethis:

Page 23: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

23 FlowControl

MATLABCourse,PartI-Solutions

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

[EndofTask]

Solution:

Wecandefinethefunctionlikethis:

function result = calc_circle(r,x) switch x case 1 result=pi*r*r; case 2 result=2*pi*r; otherwise disp('only 1 or 2 is legal values for x') end

Testingthefunction:

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

Usinganillegalvaluegives:

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

Task15: FibonacciNumbers

Inmathematics,Fibonaccinumbersarethenumbersinthefollowingsequence:

0,1,1,2,3,5,8,13,21,34,55,89,144,…

Bydefinition,thefirsttwoFibonaccinumbersare0and1,andeachsubsequentnumberisthesumoftheprevioustwo.Somesourcesomittheinitial0,insteadbeginningthesequencewithtwo1s.

Inmathematicalterms,thesequenceFnofFibonaccinumbersisdefinedbytherecurrencerelation

Page 24: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

24 FlowControl

MATLABCourse,PartI-Solutions

𝑓Q = 𝑓Q01 + 𝑓Q0@

withseedvalues:

𝑓J = 0, 𝑓1 = 1

→WriteafunctioninMATLABthatcalculatestheNfirstFibonaccinumbers,e.g.,

>> N=10; >> fibonacci(N) ans = 0 1 1 2 3 5 8 13 21 34

→UseaForlooptosolvetheproblem.

Fibonaccinumbersareusedintheanalysisoffinancialmarkets,instrategiessuchasFibonacciretracement,andareusedincomputeralgorithmssuchastheFibonaccisearchtechniqueandtheFibonacciheapdatastructure.Theyalsoappearinbiologicalsettings,suchasbranchingintrees,arrangementofleavesonastem,thefruitletsofapineapple,thefloweringofartichoke,anuncurlingfernandthearrangementofapinecone.

[EndofTask]

Solution:

Code:

function f = fibonacci(N) f=zeros(N,1); f(1)=0; f(2)=1; for k=3:N f(k)=f(k-1)+f(k-2); end

Task16: WhileLoop

Page 25: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

25 FlowControl

MATLABCourse,PartI-Solutions

CreateaScriptorFunctionthatcreatesFibonacciNumbersuptoagivennumber,e.g.,

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

UseaWhileLooptosolvetheproblem.

[EndofTask]

Solution:

Code:

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

Testingthefunctiongives:

>> maxnumber=200; fibonacci2(maxnumber) ans = 0 1 1 2 3 5 8 13 21 34 55 89 144 233

Task17: ForLoops

Extendyourcalc_averagefunctionfromaprevioustasksoitcancalculatetheaverageofavectorwithrandomelements.UseaForlooptoiteratethroughthevaluesinthevectorandfindsumineachiteration:

mysum = mysum + x(i);

TestthefunctionintheCommandwindow

[EndofTask]

Solution:

Page 26: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

26 FlowControl

MATLABCourse,PartI-Solutions

Youmaydefinethefunctionlikethis:

function av = calc_average2(x) mysum=0; N=length(x); for k=1:N mysum = mysum + x(k); end av = mysum/N;

Testingthefunction:

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

Task18: If-elseStatement

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

Examplediscardingnumberslargerthan10gives:

x = 4 6 12 >> calc_average3(x) ans = 5

[EndofTask]

Solution:

Thefunctionbecomes:

function av = calc_average2(x) mysum=0; total=0; N=length(x);

Page 27: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

27 FlowControl

MATLABCourse,PartI-Solutions

for k=1:N if x(k) < 10 mysum = mysum + x(k); total=total+1; end end av = mysum/total;

Page 28: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

28

9 MathematicsTask19: BasicMathfunction

Createafunctionthatcalculatesthefollowingmathematicalexpression:

𝑧 = 3𝑥@ + 𝑥@ + 𝑦@ + 𝑒TU(V)

[EndofTask]

Solution:

Thefunctionbecomes:

function z=calcexpression(x,y) z=3*x^2 + sqrt(x^2+y^2)+exp(log(x));

Testingthefunctiongives:

>> x=2;, y=2; calcexpression(x,y) ans = 16.8284

Task20: Statistics

Createavectorwithrandomnumbersbetween0and100.Findthefollowingstatistics:mean,median,standarddeviation,minimum,maximumandthevariance.

[EndofTask]

Solution:

Thecode:

x=rand(100,1)*100; mean(x) median(x) std(x) mean(x)

Page 29: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

29 Mathematics

MATLABCourse,PartI-Solutions

min(x) max(x) var(x)

Task21: Conversion

Itisquiteeasytoconvertfromradianstodegreesorfromdegreestoradians.Wehavethat:

2𝜋𝑟𝑎𝑑𝑖𝑎𝑛𝑠 = 360𝑑𝑒𝑔𝑟𝑒𝑠𝑠

Thisgives:

𝑑 𝑑𝑒𝑔𝑟𝑒𝑒𝑠 = 𝑟[𝑟𝑎𝑑𝑖𝑎𝑛𝑠] ∙180𝜋

𝑟[𝑟𝑎𝑑𝑖𝑎𝑛𝑠] = 𝑑[𝑑𝑒𝑔𝑟𝑒𝑒𝑠] ∙𝜋180

→Createtwofunctionsthatconvertfromradianstodegrees(r2d(x))andfromdegreestoradians(d2r(x))respectively.

Testthefunctionstomakesurethattheyworkasexpected.

[EndofTask]

Solution:

Thefunctionsareasfollows:

function d = r2d(r) d=r*180/pi;

and

function r = d2r(d) r=d*pi/180;

Testingthefunctions:

>> r2d(2*pi) ans = 360 >> d2r(180) ans = 3.1416

Page 30: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

30 Mathematics

MATLABCourse,PartI-Solutions

Task22: Trigonometricfunctionsonrighttriangle

Givenrighttriangle:

→CreateafunctionthatfindstheangleA(indegrees)basedoninputarguments(a,c),(b,c)and(a,b)respectively.

Use,e.g.,athirdinput“type”todefinethedifferenttypesabove.

→Useyoupreviousfunctionr2d()tomakesuretheoutputofyourfunctionisindegreesandnotinradians.

Testthefunctionstomakesureitworksproperly.

Tip!Wehavethat:

sin 𝐴 =𝑎𝑐 , 𝐴 = 𝑎𝑟𝑐𝑠𝑖𝑛

𝑎𝑐

cos 𝐴 =𝑏𝑐 , 𝐴 = 𝑎𝑟𝑐𝑐𝑜𝑠

𝑏𝑐

tan𝐴 =𝑎𝑏 , 𝐴 = 𝑎𝑟𝑐𝑡𝑎𝑛

𝑎𝑏

[EndofTask]

Solution:

Wehavethat:

sin 𝐴 =𝑎𝑐 , 𝐴 = 𝑎𝑟𝑐𝑠𝑖𝑛

𝑎𝑐

cos 𝐴 =𝑏𝑐 , 𝐴 = 𝑎𝑟𝑐𝑐𝑜𝑠

𝑏𝑐

tan𝐴 =𝑎𝑏 , 𝐴 = 𝑎𝑟𝑐𝑡𝑎𝑛

𝑎𝑏

Page 31: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

31 Mathematics

MATLABCourse,PartI-Solutions

ThePythagoras'theoremgives:

𝑐@ = 𝑎@ + 𝑏@

Thefunctionbecomesasfollows:

function angleA = right_triangle(x,y, type) switch type case 'sin' angleA=asin(x/y); case 'cos' angleA=acos(x/y); case 'tan' angleA=atan(x/y); end % Convert from radians to degrees angleA = r2d(angleA);

Testingthefunction:

>> a=5 a = 5 >> b=8 b = 8 >> c=sqrt(a^2+b^2) c = 9.4340 >> right_triangle(a,c,'sin') ans = 32.0054 >> right_triangle(b,c,'cos') ans = 32.0054 >> right_triangle(a,b,'tan') ans = 32.0054

→Weseetheresultisthesameandthefunctionshouldworkproperly.

Task23: Lawofcosines

Given:

Page 32: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

32 Mathematics

MATLABCourse,PartI-Solutions

Createafunctionwhereyoufindcusingthelawofcosines.

𝑐@ = 𝑎@ + 𝑏@ − 2𝑎𝑏𝑐𝑜𝑠𝐶

Testthefunctionstomakesureitworksproperly.

[EndofTask]

Solution:

Thefunctionbecomes:

function c = law_of_cosines(a,b,C) c = sqrt(a^2 + b^2 - 2*a*b*cos(C));

Testingthefunction:

>> a=2;, b=3;, C=pi;, law_of_cosines(a,b,C) ans = 5

Task24: Plotting

Plot 𝑠𝑖𝑛(𝜃)and 𝑐𝑜𝑠(𝜃) for 0 ≤ 𝜃 ≤ 2𝜋 inthesameplot.

Makesuretoaddlabelsandalegend,andusedifferentlinestylesandcolorsfortheplots.

[EndofTask]

Solution:

Wecanusetheholdfunctionforthispurpose:

x=0:0.01:2*pi; clf

Page 33: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

33 Mathematics

MATLABCourse,PartI-Solutions

plot(x, sin(x), 'c+:') hold on plot(x, cos(x), 'r:') hold off legend('sin', 'cos') xlabel('x') ylabel('f(x)')

Thisgives:

Task25: Complexnumbers

Giventwocomplexnumbers

𝑐 = 4 + 𝑗3, 𝑑 = 1 − 𝑗

FindtherealandimaginarypartofcanddinMATLAB.

→UseMATLABtofind 𝑐 + 𝑑, 𝑐 − 𝑑, 𝑐𝑑𝑎𝑛𝑑𝑐/𝑑.

UsethedirectmethodsupportedbyMATLABandthespecificcomplexfunctionsabs,angle,imag,real,conj,complex,etc.togetherwiththeformulasforcomplexnumbersthatarelistedaboveinthetext(asyoudoitwhenyoushouldcalculateitusingpen&paper).

→Findalso 𝑟 and 𝜃.Findalsothecomplexconjugate.

Page 34: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

34 Mathematics

MATLABCourse,PartI-Solutions

[EndofTask]

Solution:

Script:

c=5+3i; d=1-i; disp('c+d') %Directly----------------- z = c + d %Manually----------------- z_real = real(c) + real(d); z_imag = imag(c) + imag(d); z = complex(z_real,z_imag) % r and angle + complex conungate r=abs(z) theta=angle(z) complconj=conj(z) disp('c-d') %Directly-------------- z = c - d %Manually-------------- z_real = real(c) - real(d); z_imag = imag(c) - imag(d); z = complex(z_real,z_imag) %or: z = z_real + z_imag*i disp('c*d') %Directly------------- z = c*d %Manually------------- z_abs = abs(c)*abs(d); z_angle = angle(c) + angle(d); z_real = z_abs*cos(z_angle); z_imag = z_abs*sin(z_angle); z = complex(z_real,z_imag) disp('c/d') %Directly------------- z = c/d %Manually------------- z_abs = abs(c)/abs(d); z_angle = angle(c) - angle(d); z_real = z_abs*cos(z_angle);

Page 35: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

35 Mathematics

MATLABCourse,PartI-Solutions

z_imag = z_abs*sin(z_angle); z = complex(z_real,z_imag)

Thisgives:

c+d z = 6.0000 + 2.0000i z = 6.0000 + 2.0000i r = 6.3246 theta = 0.3218 complconj = 6.0000 - 2.0000i c-d z = 4.0000 + 4.0000i z = 4.0000 + 4.0000i c*d z = 8.0000 - 2.0000i z = 8.0000 - 2.0000i c/d z = 1.0000 + 4.0000i z = 1.0000 + 4.0000i

Task26: Complexnumbers

Findtherootsoftheequation:

𝑥@ + 4𝑥 + 13

Discusstheresults.

Addthesumoftheroots.

[EndofTask]

Solution:

Therootsaregivenby:

Page 36: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

36 Mathematics

MATLABCourse,PartI-Solutions

𝑥@ + 4𝑥 + 13 = 0

Wecane.g.,usethesolveeqfunctionwecreatedinaprevioustask:

a=1; b=4; c=13; solveeq(a,b,c)

Thisgives:

ans=

-2.0000+3.0000i

-2.0000-3.0000i

Thesolveeq()functionisasfollows:

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

Orwecanusetherootfunction:

a=1; b=4; c=13; p=[a,b,c] roots(p)

whichgivesthesameresults.

Note!thesolutioniscomplexconjugate.

Thesumoftwocomplexconjugatenumbersisalwaysreal.Inourcase:

ans=

-4

Page 37: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

37 Mathematics

MATLABCourse,PartI-Solutions

Whilethedifferenceisimaginary(norealpart).

ans=

0+6.0000i

Task27: Polynomials

DefinethefollowingpolynomialinMATLAB:

𝑝 𝑥 = −2.1𝑥j + 2𝑥k + 5𝑥 + 11

→Findtherootsofthepolynomial(𝑝 𝑥 = 0)(andcheckiftheanswersarecorrect)

→Find 𝑝 𝑥 = 2

Usethepolynomialfunctionslistedabove.

[EndofTask]

Solution:

Code:

p = [-2.1, 2, 0, 5, 11] roots(p) x = 2; polyval(p,x)

Thisgives:

p = -2.1000 2.0000 0 5.0000 11.0000 ans = 2.0820 -0.0199 + 1.5193i -0.0199 - 1.5193i -1.0898 ans = 3.4000

Meaningtherootsare:

2.0820

-0.0199 + 1.5193i

Page 38: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

38 Mathematics

MATLABCourse,PartI-Solutions

-0.0199 - 1.5193i

-1.0898

Wecanusee.g.,thepolyval()functiontocheckiftheanswersarecorrect:

x = 2.0820; polyval(p,x)

etc.

Theanswersshallthenofcoursebe 0 (oratleastaverysmallnumber).

While

𝑝 𝑥 = 2 = 3.4

Insteadofusingthepolyval()functionwecouldofcoursealsofoundtheanswerlikethis:

x = 2; p = -2.1*x^4 + 2*x^3+5*x+11

Task28: Polynomials

Giventhefollowingpolynomials:

𝑝1 𝑥 = 1 + 𝑥 − 𝑥@

𝑝@ 𝑥 = 2 + 𝑥k

→Findthepolynomial 𝑝(𝑥) = 𝑝1(𝑥) ∙ 𝑝@(𝑥) usingMATLABandfindtheroots

→Findtherootsofthepolynomial(𝑝 𝑥 = 0)

→Find 𝑝 𝑥 = 2

→Findthedifferentiation/derivativeof 𝑝@ 𝑥 ,i.e., 𝑝@l

Usethepolynomialfunctionslistedabove.

[EndofTask]

Solution:

Thepolynomialsmayberewrittenas:

𝑝1 𝑥 = −𝑥@ + 𝑥 + 1

𝑝@ 𝑥 = 𝑥k + 0𝑥@ + 0𝑥 + 2

Page 39: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

39 Mathematics

MATLABCourse,PartI-Solutions

TheMATLABcodebecomes:

p1=[-1, 1, 1]; p2=[1, 0, 0, 2]; p=conv(p1,p2) r=roots(p) polyval(p,2)

Thisgives:

p = -1 1 1 -2 2 2 r = 1.6180 0.6300 + 1.0911i 0.6300 - 1.0911i -1.2599 -0.6180 ans = -10

ThePolynomialbecomes:

𝑝 𝑥 = −𝑥m + 𝑥j + 𝑥k − 2𝑥@ + 2𝑥 + 2

Task29: PolynomialFitting

Findthe6.orderPolynomialthatbestfitsthefollowingfunction:

𝑦 = sin(𝑥)

Usethepolynomialfunctionslistedabove.

→Plotboththefunctionandthe6.orderPolynomialtocomparetheresults.

[EndofTask]

Solution:

x=0:0.1:2*pi; y=sin(x); figure(1) plot(x,y)

Page 40: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

40 Mathematics

MATLABCourse,PartI-Solutions

% Finding a 6. order polynomial p=polyfit(x,y,6) y2=polyval(p,x); figure(2) plot(x,y2)

Plots:

→Weseetheresultsisgood

Page 41: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

41

10 AdditionalTasksTask30: User-definedfunction

CreateafunctionthatusesPythagorastocalculatethehypotenuseofaright-angledtriangle,e.g.:

function h = pyt(a,b) % .. …

h = …

Pythagorastheoremisasfollows: 𝑐@ = 𝑎@ + 𝑏@

Note!Thefunctionshouldhandlethataandbcouldbevectors.

[EndofTask]

Solution:

Thefunctionmaybewrittenlikethis:

function h = pyt(a,b) % This function calculates the hypotenuse of a right-angled triangle h=sqrt(a^2 + b^2);

TestingthefunctionintheCommandwindowgives:

>> pyt(2,3)

Page 42: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

42 AdditionalTasks

MATLABCourse,PartI-Solutions

ans = 3.6056

Whatifaandbarevectors?Letstry:

>> a=rand(10,1)*10; >> b=rand(10,1)*10; >> pyt(a,b) ??? Error using ==> mpower Matrix must be square. Error in ==> pyt at 4 h=sqrt(a^2 + b^2);

Asyouseethisgivesanerror.Let’smodifyourfunctionsoitpossibleforaandbtobevectors:

function h = pyt(a,b) % This function calculates the hypotenuse of a right-angled triangle h=sqrt(a.^2 + b.^2);

Testingthefunctiongives:

>> a=rand(10,1)*10; >> b=rand(10,1)*10; >> pyt(a,b) ans = 8.2983 13.2760 9.6555 10.3433 10.1996 1.7218 5.0541 10.6661 12.4274 13.6075

Asyouseeitnowworkswitharraysto,thankstoa.^2andb.^2.

Task31: MATLABScript

GiventhefamousequationfromAlbertEinstein:

𝐸 = 𝑚𝑐@

Thesunradiates 385𝑥10@j𝐽/𝑠 ofenergy.

Page 43: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

43 AdditionalTasks

MATLABCourse,PartI-Solutions

→Calculatehowmuchofthemassonthesunisusedtocreatethisenergyperday.

→Howmanyyearswillittaketoconvertallthemassofthesuncompletely?Doweneedtoworryifthesunwillbeusedupinourgenerationorthenext?

Themassofthesunis 2𝑥10kJ𝑘𝑔

[EndofTask]

Solution:

Thespeedoflightis: 𝑐 = 3 ∙ 10r𝑚/𝑠

Themassonthesunisneededtocreatethisenergyperday:

𝑚 = 𝐸/𝑐@

where:

𝐸 = 385𝑥10@j𝐽/𝑠

𝑐 = 3 ∙ 10r𝑚/𝑠

Energyperdayis:

𝐸 = 385𝑥10@j𝐽𝑠 ∙ 60 ∙ 60

𝑠ℎ𝑜𝑢𝑟 ∙ 24

ℎ𝑜𝑢𝑟𝑠𝑑𝑎𝑦 = 3.33 ∙ 10k1𝐽

Thisgives:

𝑚 =𝐸𝑐@ =

3.33 ∙ 10k1𝐽3 ∙ 10r𝑚/𝑠 @ = 3.7 ∙ 101j

𝐽𝑚@/𝑠@

Where

1𝐽 = 1𝑘𝑔𝑚@/𝑠@

Thisgives:

𝑚 = 3.7 ∙ 101j𝑘𝑔

Timestoittakestoconvertallthemassofthesuncompletely:

𝑡𝑖𝑚𝑒 =𝑚𝑎𝑠𝑠𝑜𝑓𝑠𝑢𝑛

𝑟𝑎𝑡𝑒𝑜𝑓𝑐𝑜𝑛𝑠𝑢𝑚𝑡𝑖𝑜𝑛

Thisgives:

𝑡𝑖𝑚𝑒 =2𝑥10kJ𝑘𝑔

3.7 ∙ 101j𝑘𝑔/𝑑𝑎𝑦 ∙𝑦𝑒𝑎𝑟

365𝑑𝑎𝑦𝑠 = 1.5 ∙ 101k𝑦𝑒𝑎𝑟𝑠

Page 44: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

44 AdditionalTasks

MATLABCourse,PartI-Solutions

TheMATLABscriptbecomesasfollows:

clc %Define variables c = 3e8; %[m/s] E = 385e24; %[J/s] %Need to convert: E = E*60*60*24; %[J] %Mass of the sun used to create this amount of energy m = E/c^2 %[kg] %Total mass of sun: m_sun = 2e30; %[kg] %Number of days before sun is gone days = m_sun/m; %[days] %Number of years before sun is gone years = days/365 %[years]

TheAnswersis:

m = 3.6960e+014 years = 1.4825e+013

Themassonthesunisneededtocreatethisenergyperday:

3.7 ∙ 101j𝑘𝑔

Numbersofyearsitwilltaketoconvertallthemassofthesuncompletely:

1.5 ∙ 101k𝑦𝑒𝑎𝑟𝑠

Task32: Cylindersurfacearea

Createafunctionthatfindsthesurfaceareaofacylinderbasedontheheight(h)andtheradius(r)ofthecylinder.

Page 45: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

45 AdditionalTasks

MATLABCourse,PartI-Solutions

[EndofTask]

Solution:

Thefunctionbecomes:

function A = cylindar_surface(h,r) % This function calculates the surface of a sylindar A = 2*pi*r^2 +2*pi*r*h;

Testingthefunction:

>> h=8 h = 8 >> r=3 r = 3 >> cylindar_surface(h,r) ans = 207.3451

Page 46: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

46 AdditionalTasks

MATLABCourse,PartI-Solutions

Task33: CreateadvancedexpressionsinMATLAB

CreatethefollowingexpressioninMATLAB:

𝑓 𝑥 =ln 𝑎𝑥@ + 𝑏𝑥 + 𝑐 − sin(𝑎𝑥@ + 𝑏𝑥 + 𝑐)4𝜋𝑥@ + cos(𝑥 − 2)(𝑎𝑥@ + 𝑏𝑥 + 𝑐)

Given 𝑎 = 1, 𝑏 = 3, 𝑐 = 5

→Find 𝑓 9

(Theanswershouldbe 𝑓 9 = 0.0044)

Tip!Youshouldsplittheexpressionsintodifferentparts,suchas:

poly=𝑎𝑥@ + 𝑏𝑥 + 𝑐

num=…

den=….

f=…

Thismakestheexpressionsimplertoreadandunderstand,andyouminimizetheriskofmakinganerrorwhiletypingtheexpressioninMATLAB.

[EndofTask]

Solution:

TheScript(advexpression.m)becomes:

% Define the variables: a = 1; b = 3; c = 5; x = 9; % Split functions into parts for easy maintenance poly = a*x^2 + b*x + c; num = log(poly)-sin(poly); den = 4*pi*x^2 +cos(x-2)*poly; f = num/den

TestingtheScript:

>> advexpression f =

Page 47: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

47 AdditionalTasks

MATLABCourse,PartI-Solutions

0.0044

Task34: SolvingEquations

Findthesolution(s)forthegivenequations:

𝑥1 + 2𝑥@ = 5

3𝑥1 + 4𝑥@ = 6

7𝑥1 + 8𝑥@ = 9

[EndofTask]

Solution:

Settheequationsonthefollowingform:

𝐴𝑥 = 𝑏

Thesolutionis:

𝐴𝑥 = 𝑏 → 𝑥 = 𝐴01𝑏

LetsfindAandb:

𝐴 =1 23 47 8

𝑏 =569

MATLAB:

>> A=[1 2; 3 4; 7 8] A = 1 2 3 4 7 8 >> b=[5;6;9] b = 5 6 9 >> x=inv(A)*b ??? Error using ==> inv Matrix must be square.

Page 48: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

48 AdditionalTasks

MATLABCourse,PartI-Solutions

→Wegetanerror(asexpected!)becauseAmustbesquareinordertofindtheinverseofA.

Inthiscasewehavetodothefollowing:

>> x=A\b x = -3.5000 4.1786

Task35: Preallocatingofvariablesandvectorization

HerewewillusepreallocatingofvariablesandvectorizationandcomparewithusingaForLoop.

Wewillusethefunctionsticandtoctofindtheexecutiontime.

Wewillcreateasimpleprogramthatcalculates 𝑦 = 𝑐𝑜𝑠(𝑡) fort=1to100000.

CreatethefollowingScript:

% Test 1: Using a For Loop clear tic tmax=100000; for t=1:tmax y(t,1)=cos(t); end toc

→Whatwastheexecutiontime?

WewillimprovetheScriptbypreallocatingspaceforthevariabley.CreatethefollowingScript:

% Test 2: For Lopp with preallocating clear tic tmax=100000; y=zeros(tmax,1); % preallocating for t=1:tmax y(t,1)=cos(t); end toc

→Whatwastheexecutiontime?

Page 49: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

49 AdditionalTasks

MATLABCourse,PartI-Solutions

WewillimprovetheScriptfurtherbyremovingtheForLoopbyusingvectorizationinstead:

% Test 3: Vectorization clear tic tmax=100000; t=1:tmax; %vectorization y=cos(t); toc

→Whatwastheexecutiontime?

Discusstheresult.

[EndofTask]

Solution:

Test1:

Elapsedtimeis18.172769seconds.

Test2:

Elapsedtimeis0.007852seconds.

Test3:

Elapsedtimeis0.006926seconds.

→Weseetheexecutiontimeisdrasticallyreducedbypreallocatingspaceforthevariabley,whileusingvectorizationreducedtheexecutiontimeevenmore.

Task36: NestedForLoops

Giventhematrices 𝐴 ∈ 𝑅QVz and 𝐵 ∈ 𝑅zV{,then

𝐶 = 𝐴𝐵 ∈ 𝑅QV{

where

𝑐|} = 𝑎|~𝑏~}

Q

~�1

InMATLABitiseasytomultiplytwomatrices:

Page 50: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

50 AdditionalTasks

MATLABCourse,PartI-Solutions

>> A=[0 1;-2 -3] A = 0 1 -2 -3 >> B=[1 0;3 -2] B = 1 0 3 -2 >> A*B ans = 3 -2 -11 6

Butheryouwillcreateyourownfunctionthatmultiplytwomatrices:

function C = matrixmult(A,B) …

Tip!Youneedtouse3nestedForLoops.

[EndofTask]

Solution:

Thefunctionbecomes:

function C=matrixmult(A,B) % Multiplies two matrices using For Lops [n,cols_a]=size(A); [rows_b,p]=size(B); if cols_a == rows_b m=cols_a; C=zeros(n,p); for i=1:n for j=1:p w=0; for k=1:m w=w+A(i,k)*B(k,j); end C(i,j)=w; end end elseif cols_a ~= rows_b disp('Error:') C=NaN; end

Testingthefunctiongives:

Page 51: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

51 AdditionalTasks

MATLABCourse,PartI-Solutions

>> A = [1 2; 3 4] A = 1 2 3 4 >> B = [0 3; 4 5] B = 0 3 4 5 >> C = A*B C = 8 13 16 29 >> C = matrixmult(A,B) C = 8 13 16 29

Weseethatourfunctiongivesthesameanswerasthebuilt-infunctionality.

Page 52: MATLAB Solutions - Part 1 - Telemark University Collegehome.hit.no/~hansha/documents/lab/Lab Work/MATLAB/solutions/Part I... · Task 1: Basic Operations..... 7 Task 2: Statistics

Hans-PetterHalvorsen,M.Sc.

E-mail:[email protected]

Blog:http://home.hit.no/~hansha/

UniversityCollegeofSoutheastNorway

www.usn.no