introduction to matlab programming lec …...12/17/15 1 introduction to matlab programming lec 1.1:...

21
12/17/15 1 INTRODUCTION TO MATLAB PROGRAMMING Lec 1.1: MATLAB Basics Dr. Niket Kaisare Department of Chemical Engineering IIT–Madras NPTEL Course: MATLAB Programming for Numerical Computations — Week-1 About this Module We will cover the following topics MATLAB basics Arrays: Unlocking potential of MATLAB Loops and Execution Control MATLAB files: Scripts and Functions Program Output and Plotting

Upload: others

Post on 18-Feb-2020

53 views

Category:

Documents


1 download

TRANSCRIPT

12/17/15

1

INTRODUCTION TOMATLAB PROGRAMMINGLec 1.1:MATLAB BasicsDr.NiketKaisareDepartmentofChemicalEngineeringIIT–Madras

NPTELCourse:MATLABProgrammingforNumericalComputations—Week-1

AboutthisModule

•Wewillcoverthefollowing topics

• MATLABbasics

• Arrays:UnlockingpotentialofMATLAB

• LoopsandExecutionControl

• MATLABfiles:ScriptsandFunctions

• ProgramOutputandPlotting

12/17/15

2

Starting andExitingMATLAB

•WewillgooverstartingaMATLABsession, layoutofMATLABwindow,MATLABeditor,etc.

• Alsoseevideo“GettingStartedwithMATLAB”onMATLABsitehttp://in.mathworks.com/videos/getting-started-with-matlab-68985.html

MATLAB Programming Example

Indiancaptain,Mahendra SinghDhoni, hitsaballwithinitialvelocityof35m/sandangleof45○.Iftheboundary isatadistanceof75m,willhescoreasix?

• Settinguptheproblem:

• !"#$ = 35;*+ = !"#$ cos //4 ; !+ = !"#$ sin //4

• 45 = *; 6 5 = !

• *5 = −8*;!5 = −9;

12/17/15

3

Result

MATLAB Code%% Define Parameters and Initial Conditionsparam.g = 9.81; % gravitational accelerationparam.kappa = 0.006; % air drag coefficientu0 = 35*cos(pi/4);v0 = 35*sin(pi/4);

%% Setting up and Solving the problemX0 = [0; 0; % starting position is the origin

u0; v0]; % starting velocity is giventSpan = [0 20]; % simulation time[tOut, XOut] = ode45(@ballTrajectoryFun,tSpan,X0, [], param);

%% Displaying the resultsfigure(1);plot(XOut(:,1),XOut(:,2),'bo');xlabel('x (m)'); ylabel('y (m)');

%% Animating resultsexitCode = ballAnimation(tOut,XOut);

12/17/15

4

MATLAB Code:MainCodeBlocks%% Define Parameters and Initial Conditionsparam.g = 9.81; % gravitational accelerationparam.kappa = 0.006; % air drag coefficientu0 = 35*cos(pi/4);v0 = 35*sin(pi/4);

%% Setting up and Solving the problemX0 = [0; 0; % starting position is the origin

u0; v0]; % starting velocity is giventSpan = [0 20]; % simulation time[tOut, XOut] = ode45(@ballTrajectoryFun,tSpan,X0, [], param);

%% Displaying the resultsfigure(1);plot(XOut(:,1),XOut(:,2),'bo');xlabel('x (m)'); ylabel('y (m)');

%% Animating resultsexitCode = ballAnimation(tOut,XOut);

Inputb

lock

Computation

Outputb

lock

MATLAB Code:KeyParts%% Define Parameters and Initial Conditionsparam.g = 9.81;

u0 = 35*cos(pi/

[tOut, XOut] = ode45(@bal

plot(XOu

Comment

Assignment

(Math)Expression

Callingafunction

Callingafunction

12/17/15

5

MATLAB Code%% Define Parameters and Initial Conditionsparam.g = 9.81; % gravitational accelerationparam.kappa = 0.006; % air drag coefficientu0 = 35*cos(pi/4);v0 = 35*sin(pi/4);

%% Setting up and Solving the problemX0 = [0; 0; % starting position is the origin

u0; v0]; % starting velocity is giventSpan = [0 20]; % simulation time[tOut, XOut] = ode45(@ballTrajectoryFun,tSpan,X0, [], param);

%% Displaying the resultsfigure(1);plot(XOut(:,1),XOut(:,2),'bo');xlabel('x (m)'); ylabel('y (m)');

%% Animating resultsexitCode = ballAnimation(tOut,XOut);

BasicDataTypes

•Matlab easilyworkswitharrays

• Scalars,vectorsandarrays

• Assigningvariables

• Rowvs.columnvectors

• Arrays/Matrices

• Suppress “echo”

• Variablesarecase-sensitive

12/17/15

6

BasicMathematical Expressions

ScalarOperations• + - * / ^

• log, exp

• pow, sqrt

• sin, cos, tan

• asin, acos, atan

• rem, round, ceil, floor

Variable Meaningpi Number /

eps Machineprecision

i Imaginaryunit

inf Infinity

NaN NotaNumber (e.g.,0/0)

ans Lastdisplayedresult

end Lastelement ofarray

realmax Largestrealnumber

intmax Largestinteger

SpecialVariables

EndofLecture1-1

12/17/15

7

INTRODUCTION TOMATLAB PROGRAMMINGLec 1.2:ArrayOperationsDr.NiketKaisareDepartmentofChemicalEngineeringIIT–Madras

NPTELCourse:MATLABProgrammingforNumericalComputations—Week-1

Arraysarethemostpowerful aspectofMATLAB

•Wewilllearn

• Buildingarrays

• Colonnotations

• Arrayoperationsandfunctions

• Alsoview“WorkingwithArraysinMATLAB”onMATLABwebsite:http://in.mathworks.com/videos/working-with-arrays-in-matlab-69022.html

12/17/15

8

Building Arrays

• Recallthatwecanbuild arraysas:>> A = [1, 2; 3 4];

•Wecanalsobuild arraysfromexistingarrays(ifcorrectsize):>> B = [b, c];

Command Meaningones(m,n) Build m×nmatrix of1’s

zeros(m,n) Build m×nmatrix of0’s

eye(n) Identitymatrix

diag(vec) Create diagonal matrix

diag(A) DiagonalelementsofA

rand(m,n) Uniform randomnumberarray

randn(m,n) GaussianRandomnumber array

magic(m) Magicsquare matrix

hilb Hilbert matrix

ArrayBuildingFunctions

BasicMathematical Expressions

“Scalar”Operations

• log, exp

• power, sqrt

• sin, cos, tan

• asin, acos, atan

• rem, round, ceil, floor

MatrixOperations• + – * / ^

• logm, expm

• mpower, sqrtm

• sum,prod,cumsum,cumprod

• min, max, mean, std

• length, size, eig

12/17/15

9

BasicMathematical Expressions

“Scalar”Operations• + – .* ./ .^

• log, exp

• power, sqrt

• sin, cos, tan

• asin, acos, atan

• rem, round, ceil, floor

MatrixOperations• + – * / ^

• logm, expm

• mpower, sqrtm

• sum,prod,cumsum,cumprod

• min, max, mean, std

• length, size, eig

EndofLecture1-2

12/17/15

10

INTRODUCTION TOMATLAB PROGRAMMINGLec 1.2b:ArrayOperationsRevisitedDr.NiketKaisareDepartmentofChemicalEngineeringIIT–Madras

NPTELCourse:MATLABProgrammingforNumericalComputations—Week-1

Tapping someArrayOperations inMATLAB• Alsoview“WorkingwithArraysinMATLAB”onMATLABwebsite:http://in.mathworks.com/videos/working-with-arrays-in-matlab-69022.html

• Consider thefollowing example(Marksearnedbystudents)

Name Math Programming Thermodynamics MechanicsAmit 24 44 36 36Bhavna 52 57 68 76Chetan 66 53 69 73Deepak 85 40 86 72Elizabeth 15 47 25 28Farah 79 72 82 91

12/17/15

11

Somethingstotry• Createa6×3matrixallMarks tocontainmarksforfirstthreecourses

• AppendmarksfortheMechanicscoursetoallMarks whenreceived

• Dothefollowing computations

• Mechanicscoursewasoutof50.Scalethemarkstohalf

• Extractrow3andgivethemarkstoChetan.Alsocalculatehistotalmarks

• Extractmarksofourbeststudents,DeepakandFarahforfirstthreecourses

• Calculateaveragemarksobtainedineachofthefourcourses

• Scaleallthemarksoutof10*

Wewillusematrixfundaes forthis:

< => ?@ A

2 00 0.1

=2< 0.1=2> 0.1?2@ 0.1A

EndofLecture1-2b

12/17/15

12

INTRODUCTION TOMATLAB PROGRAMMINGLec 1.3:LoopsandExecutionControlDr.NiketKaisareDepartmentofChemicalEngineeringIIT–Madras

NPTELCourse:MATLABProgrammingforNumericalComputations—Week-1

VariousLoopsinMATLAB

• ForLoop(commands belowwillexecute10times)

for i=1:10

<statement 1>;

<statement n>;

end

•WhileLoop (commandsbelowwillexecuteifthecondition istrue)

while i<10

<statement 1>;

<statement n>;

i=i+1;

end

12/17/15

13

WhentouseForLoop

• Forloopisusedwhenasetofoperationsaretoberepeatedaspecific numberoftimes

• Examples

• Findfirst10termsofFibonacciseries

• FindfactorialofanumberG

• …

WhentouseWhile Loop

•Whileloop isusedwhenasetofoperationsistoberepeatedifacertaincondition ismet

• FindalltermsofFibonacciserieslessthanvalue200

• Locationofaballthrownupwardsisgivenby6 = !+H −IJ9HK.Calculatethe

locationoftheballforevery0.1secondsuntilitreachestheground (i.e.,6 > 0)

12/17/15

14

MacLaurin Series

• Calculateapproximatevalueof@+.M using theinfiniteseries:

@N = 1 + < +<K

2!+<Q

3!+<R

4!+ ⋯

Thesecalculationsaretobeperformedwith2to7termsintheseries

EndofLecture1-3

12/17/15

15

INTRODUCTION TOMATLAB PROGRAMMINGLec 1.4:Working withFiles– Scripts&FunctionsDr.NiketKaisareDepartmentofChemicalEngineeringIIT–Madras

NPTELCourse:MATLABProgrammingforNumericalComputations—Week-1

Working withMATLAB files

• Type“edit <fileName>” atthecommandprompttoopenMATLABcodeeditorwiththefilefileName.m.

•MATLABfilesareoftwotypes:Scripts andFunctions

•MorehelpfromMATLABwebsiteon“WritingaMATLABProgram”:http://in.mathworks.com/videos/writing-a-matlab-program-69023.html

12/17/15

16

MATLAB Files:Scriptsvs.Functions

•ScriptsFilescontainingsequenceofMATLABcommands

•MATLABstatementsareexecutedasiftypedoncommandprompt

•FunctionsFilesthattakecertaininput(s),executessequenceofsteps, andreturnsoutput(s) attheend

•MATLABstatementsareexecutedinfunction’s ownvariablespace

ScopeofVariables

• script sharesthevariableswithworkspacefromwhereitwascalled

• Typically, thatmeansMATLABworkspace

• function hasitsownworkspace

• Variablesusedinafunctionhavelocalscope

• Functions “talk”throughinput andoutputvariables:[out1,out2,...] = function fcnName(in1,in2,...)

12/17/15

17

ScriptandFunctionExamples:

•WriteascripttocalculatefactorialG! = 1×2×⋯×G

•WriteafunctiontocalculateA = >+ + >T4+ >K4K + ⋯+ >"4"

Note:Suchfunctions arecommonlyusedtocalculatephysicalproperties offluids.Today,wewillconsider asimplecaseof:

>+ = 1, >V = 1/W

WhentouseScripts vs.Functions(beginners)• Usescriptswhenyouwantto…• Makesmallcalculations(e.g.,factorial,plotting,basiccomputingetc.)

• Usefunctionswhenyouwantto…• Calculatevalues(r)asafunctionofvariables(t,y,…):X = A(H,6, … )

• PassonthefunctionvaluestoMATLABfunction forsolvingsomething;e.g.,:\]\$= A H,6 à function dy = myODEfun(t,y)

<...>ode45(@myOdefun, <...>)

• Calculatepropertiesasafunctionoftemperature,concentration,current,etc.

• Allotherpurposes, youarelikelytousescripts(insteadoffunctions)

12/17/15

19

INTRODUCTION TOMATLAB PROGRAMMINGLec 1.5:Plotting andOutputDr.NiketKaisareDepartmentofChemicalEngineeringIIT–Madras

NPTELCourse:MATLABProgrammingforNumericalComputations—Week-1

Variousformsofoutput

• Displayonthescreen• Variableswillecho ifcommandendswithoutsemicolon

• Otheroptions…

• Plottingdata• Usingplot command

• Otheroptions…

•MorehelpfromMATLABwebsiteon“UsingBasicPlottingFunctions”http://in.mathworks.com/videos/using-basic-plotting-functions-69018.html

12/17/15

20

Displaying onthescreen

• Recallvariousmethodsweused inthismodule:• Echo resultonscreen: >> b = [1, 2; 7 1];

• Usingdisp command: disp(b)

• disp sometext: disp(‘Hello world’)

• More“beautiful”output:disp([‘Factorial value is ’, num2str(factValue)])

• Moreadvancedoutputusingfprintf:fprintf('Factorial Value is: %4i\n',factValue)

Plotting

• Consider theexampleofaballthrownverticallyupwards

• Plotlocationvs.time

• Labelingtheaxes

• Otherplottingoptions

• Plot-tingmultiplelines

• Log-Log plot

12/17/15

21

EndofLecture1.5

MODULE–1INTRODUCTION TOMATLAB PROGRAMMINGDr.NiketKaisareDepartmentofChemicalEngineeringIIT–Madras

NPTELCourse:MATLABProgrammingforNumericalComputations—Week-1

12/17/15

22

SummaryofModule-1

•MATLABbasics

• FamiliarizedwithMATLABcommandwindowandeditor

• Variables:scalars,vectorsandarrays

• Mathematicaloperations:bothscalarandmatrixoperations

• Arrays:UnlockingpotentialofMATLAB

• Arrayoperationsvs.elementaloperations

• UsingarraysformoreefficientuseofMATLAB

SummaryofModule-1

• Executioncontrol• for andwhile loops

• if-then statements

•MATLABfiles

• ScriptsandFunctions

• Whentousescriptsvs.functions

• PlottinginMATLAB