basis of mathematical modeling

28
Basis of Mathematical Modeling LECTURE 2 Programming in MATLAB Dr. N.K. Sakhnenko, PhD, Professor Associate

Upload: jace

Post on 16-Jan-2016

66 views

Category:

Documents


0 download

DESCRIPTION

Basis of Mathematical Modeling. LECTURE 2 Programming in MATLAB. Dr. N.K. Sakhnenko, PhD, Professor Associate. Outline. M-files: scripts and functions Types of functions Control flow statements. M-files. The MATLAB product provides a powerful programming language, as well - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Basis of Mathematical Modeling

Basis of Mathematical Modeling

LECTURE 2

Programming in MATLAB

Dr. N.K. Sakhnenko, PhD, Professor Associate

Page 2: Basis of Mathematical Modeling

Outline

M-files: scripts and functions Types of functions Control flow statements

Page 3: Basis of Mathematical Modeling

M-files

The MATLAB product provides a powerful programming language, as wellas an interactive computational environment. Files that contain code in theMATLAB language are called M-files. You create M-files using a text editor,then use them as you would any other MATLAB function or command.

There are two kinds of M-files:• Scripts, which do not accept input arguments or return output arguments.They operate on data in the workspace.• Functions, which can accept input arguments and return outputarguments. Internal variables are local to the function.

Create a new M-file by selecting the File->New->M-file menu item or by clicking the new-file button.

Page 4: Basis of Mathematical Modeling

Scripts

When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace, to be used in subsequent computations. In addition, scripts can produce graphical output using functions like plot.

Page 5: Basis of Mathematical Modeling

Scripts

Create a new M-file and type following:

x=[-1:0.1:1];f=sin(x);plot(x,f)

Save the file as mydemo.m. You have just created a MATLAB script file. Typing mydemo in the Command window causes the statements in the script file mydemo.m to be executed. To run this file you can also use F5 or Debug->Run menu item.

Page 6: Basis of Mathematical Modeling

Functions

Functions are M-files that can accept input arguments and return output arguments. The names of the M-file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt.

The first line of a function M-file starts with the keyword function. It gives the function name and order of arguments. In this case, there are up to two input arguments and one output argument.

Page 7: Basis of Mathematical Modeling

Functions

Create a new M-file and type following:

function f=myfun(x)f=exp(x).*sqrt((x.^3+2)./(x.^4+3));

Save the file as myfun.m. You now have a MATLAB function with one input and one output argument.

This function calculates the value of the expression

To use the function type in the command window

>> y=myfun(1) % x can a matrix as welly =2.3541 The first line of the function declares the function name, input arguments and output arguments; without this line the file would be the script file.

3

24

3

x

xe x

Page 8: Basis of Mathematical Modeling

Multiple inputs

This function calculates the value of the expression

function f=myfun1(x,y,z)f=sqrt(x.^2+y.^2+z.^2);

To use the function type in the command window>> myfun1(1,0,2)ans = 2.2361

>> x=[1 2]; y=[0 -3]; z=[2 0];>> myfun1(x,y,z)ans = 2.2361 3.6056

2 2 2x y z

Page 9: Basis of Mathematical Modeling

Multiple outputs

2 2 2f x y z

g x y z

Create the M-file

function [f,g]=myfun2(x,y,z)f=sqrt(x.^2+y.^2+z.^2);g=x+y+z;

Type in the command window

>> [f,g]=myfun2(1,0,2)

f = 2.2361g = 3

Page 10: Basis of Mathematical Modeling

Types of Functions

MATLAB offers several different types of functions to use in your

programming.

Handle-Functions

Inline-Functions

Primary and Subfunctions

Page 11: Basis of Mathematical Modeling

Function HandlesA function handle is typically passed in an argument list to other functions, which can then execute, or evaluate, the function using the handle. Construct a function handle in MATLAB using the at sign, @, before the function name. The following example creates a function handle for the sin function and assigns it to the variable fhandle. fhandle = @sin;Evaluate a function handle using the MATLAB feval function.

>> feval(fhandle,1) % or feval(@sin,1)ans = 0.8415

When you call plot with a handle to the sin function and the argument shown below, the resulting evaluation produces a sine wave plot.

>>plot(feval(fhandle,0:0.01:2*pi)) % or plot(feval(@sin,0:0.01:2*pi))

This function that does not require an M-file.

Page 12: Basis of Mathematical Modeling

Inline functionsSyntaxg = inline(expr)g = inline(expr,arg1,arg2,...)

Example 1.

>> f = inline('3*sin(2*x.^2)')

f = Inline function: f(x) = 3*sin(2*x.^2)>> f(0)ans = 0

Example 2.

>> f1 = inline('sin(alpha*x)')

f1 = Inline function: f1(alpha,x) = sin(alpha*x)

>> f1(1,pi)ans =

1.2246e-016

If the function variables are in the wrong order, you can specify the desired variables explicitly with the inline argument list. g = inline('sin(alpha*x)','x','alpha')

Page 13: Basis of Mathematical Modeling

Primary and Subfunctions

Function M-files can contain code for more than one function. The first

function in the file is the primary function, the function invoked with the

M-file name. Additional functions within the file are subfunctions that

are only visible to the primary function or other subfunctions in the same

file. Each subfunction begins with its own function definition line. The

functions immediately follow each other. The various subfunctions can

occur in any order, as long as the primary function appears first.

Page 14: Basis of Mathematical Modeling

Primary and Subfunctions

function avg = newstats(u) % Primary function% NEWSTATS Find mean with internal functions.n = length(u);avg = mean(u,n);

function a = mean(v,n) % Subfunction% Calculate average.a = sum(v)/n;

>> u=[7 3 5]>> f=newstats(u)f = 5

Page 15: Basis of Mathematical Modeling

Function Functions

A class of functions called “function functions” works with nonlinear functions of

a scalar variable. That is, one function works on another function. The function

functions include

• Zero finding

• Optimization

• Numerical Integration

• Ordinary differential equations

MATLAB represents the nonlinear function by a function M-file.

Page 16: Basis of Mathematical Modeling

Control flow statements

In their basic forms, these MATLAB flow control statements operate like

those in most computer languages. Indenting the statements of a loop or

conditional statements is optional, but it helps readability to follow a standard

convention.

Page 17: Basis of Mathematical Modeling

Relations and logical operators

Comparisons in MATLAB are performed with the aid of the following operators.Operator Description< Less than<= Less than or equal to> Greater>= Greater or equal to== Equal to~= Not equal toThere are three logical operators available in MATLABLogical operator Description| And& Or~ NotE.g.: condition in MATLAB has the form (-1<=х) &(х<2)1 2x

Page 18: Basis of Mathematical Modeling

The if statementThe if statement evaluates a logical expression and executes a group of statements when the expression is true. An end keywords, which matches the if, terminates the last group of statements. The elseif and else keywords are optional. Syntax of the simplest form of the construction under discussion is

if expression commandsend

This construction is used if there is one alternative only. Two alternatives require the construction

if expressioncommands (evaluated if expression is true)elsecommands (evaluated if expression is false)end

Page 19: Basis of Mathematical Modeling

The if statement

If there are several alternatives one should use the following construction

if expression1commands (evaluated if expression 1 is true)elseif expression 2commands (evaluated if expression 2 is true)elseif …...elsecommands (executed if all previous expressions evaluate to false)end

Page 20: Basis of Mathematical Modeling

The if statement

function [x1,x2]=root2(a,b,c)% calculation of the discriminantD=b^2-4*a*c;if D<0 error (‘complex roots')end% funding the rootsx1=(-b+sqrt(D))/a/2;x2=(-b-sqrt(D))/a/2;

>> [x1,x2]=root2(1,2,-1)or>> [x1,x2]=root2(1,2,10)

2 0ax bx c Funding the real roots of the square equation

Page 21: Basis of Mathematical Modeling

The if statement

function ifdem(a)% Example of using if-elseif-elseif (a==0) disp('a is equal to 0')elseif a==1 disp('a is equal to 1')elseif a==2 disp('a is equal to 2')elseif a>=3 disp ('a is greater or equal to 3')else disp('a is less than 3 and distinct from 0, 1 and 2')end

>> ifdem(1)a is equal to 1>> ifdem(1.3)a is less than 3 and distinct from 0, 1 and 2>> ifdem(3)a is greater or equal to 3

Page 22: Basis of Mathematical Modeling

The switch statement

The switch statement executes groups of statements based on the value ofa variable or expression. The keywords case and otherwise delineate thegroups. Only the first matching case is executed. There must always be anend to match the switch. Syntax of the switch-case construction is

switch expression (scalar or string)case value1 (executes if expression evaluates to value1)commandscase value2 (executes if expression evaluates to value2)commands...otherwisestatementsend

Switch compares the input expression to each case value. Once the match is found it executes the associated commands. See help switch for more information.

Page 23: Basis of Mathematical Modeling

The for loopThe for loop repeats a group of statements a fixed, predetermined number oftimes. A matching end delineates the statements.

for count=start:step:final statementsend

If step=1 we can omit it. >> for i=1:5i^2end

ans = 1ans = 4ans = 9ans = 16ans = 25

Page 24: Basis of Mathematical Modeling

The for loop

>> x=[0:pi/30:2*pi];>> for a=-0.1:0.02:0.1 y=(1-exp(a*x)).*sin(x); hold on plot(x,y) end

( , ) (1 )sin , 0,2axy x a e x x

Hold on adds every new graph in current window

Page 25: Basis of Mathematical Modeling

The for loop

20

1

.!

1

k kSThe following calculates the sum

>> S=0;>> for k=1:1:20S=S+1/factorial(k);end>> S

S =

3.4366

Page 26: Basis of Mathematical Modeling

The for loop

The for loops can be nested

H = zeros(5);for k=1:5for l=1:5H(k,l) = 1/(k+l-1);endendH

Matrix H created here is called the Hilbert matrix. First command assigns a space in computer's memory for the matrix to be generated. This is added here to reduce the overhead that is required by loops in MATLAB.

Page 27: Basis of Mathematical Modeling

The while loopThe while loop repeats a group of statements an indefinite number of timesunder control of a logical condition. A matching end delineates the statements.

The general form of a while loop is:

while expression

statements

end

The statement will be repeatedly executed as long as the expression remains true.

Page 28: Basis of Mathematical Modeling

The while loop

Using of this programm

>> whiledem(1)n = 1>> whiledem(3)n = 2

function whiledem(a)n=0;while 2^n<=a n=n+1;endn

E.g., for a given number a, the following computes and displays the smallest nonnegative integer n such that 2n>a: