Basis of mathematical modeling
This presentation is the property of its rightful owner.
Sponsored Links
1 / 28

Basis of Mathematical Modeling PowerPoint PPT Presentation

  • Uploaded on
  • Presentation posted in: General

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

Download Presentation

Basis of Mathematical Modeling

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

Basis of Mathematical Modeling


Programming in MATLAB

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


  • M-files: scripts and functions

  • Types of functions

  • Control flow statements


The MATLAB product provides a powerful programming language, as well

as an interactive computational environment. Files that contain code in the

MATLAB 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 output

arguments. 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.


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


Create a new M-file and type following:




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.


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

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


Create a new M-file and type following:

function f=myfun(x)


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 well

y =


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.

Multiple inputs

This function calculates the value of the expression

function f=myfun1(x,y,z)


To use the function type in the command window

>> myfun1(1,0,2)

ans =


>> x=[1 2]; y=[0 -3]; z=[2 0];

>> myfun1(x,y,z)

ans =

2.2361 3.6056

Multiple outputs

Create the M-file

function [f,g]=myfun2(x,y,z)



Type in the command window

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

f = 2.2361

g = 3

Types of Functions

  • MATLAB offers several different types of functions to use in your

  • programming.

  • Handle-Functions

  • Inline-Functions

  • Primary and Subfunctions

Function Handles

A 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 doesnot require an M-file.

Inline functions

Example 2.

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

f1 =

Inline function:

f1(alpha,x) = sin(alpha*x)

>> f1(1,pi)

ans =


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


g = 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 =


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.

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

Function Functions

A class of functions called “function functions” works with nonlinear functionsof a scalar variable. That is, one function works on another function. Thefunction functions include

• Zero finding

• Optimization

• Numerical Integration

• Ordinary differential equations

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

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.

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 to

  • There are three logical operators available in MATLAB

  • Logical operator Description

  • | And

  • & Or

  • ~ Not

  • E.g.: condition in MATLAB has the form (-1<=х) &(х<2)

The if statement

The 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



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

if expression

commands (evaluated if expression is true)


commands (evaluated if expression is false)


The if statement

If there are several alternatives one should use the following construction

if expression1

commands (evaluated if expression 1 is true)

elseif expression 2

commands (evaluated if expression 2 is true)

elseif …



commands (executed if all previous expressions evaluate to false)


The if statement

Funding the real roots of the square equation

function [x1,x2]=root2(a,b,c)

% calculation of the discriminant


if D<0

error (‘complex roots')


% funding the roots



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


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

The if statement

function ifdem(a)

% Example of using if-elseif-else

if (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')


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


The switch statement executes groups of statements based on the value of

a variable or expression. The keywords case and otherwise delineate the

groups. Only the first matching case is executed. There must always be an

end to match the switch. Syntax of the switch-caseconstruction is

switch expression (scalar or string)

case value1 (executes if expression evaluates to value1)


case value2 (executes if expression evaluates to value2)






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.

The for loop

The for loop repeats a group of statements a fixed, predetermined number of

times. A matching end delineates the statements.

for count=start:step:final



If step=1 we can omit it.

>> for i=1:5



ans = 1

ans = 4

ans = 9

ans = 16

ans = 25

The for loop

>> x=[0:pi/30:2*pi];

>> for a=-0.1:0.02:0.1


hold on



Hold on adds every new graph in current window

The for loop

The following calculates the sum

>> S=0;

>> for k=1:1:20



>> S

S =


The for loop

The for loops can be nested

H = zeros(5);

for k=1:5

for l=1:5

H(k,l) = 1/(k+l-1);




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

The while loop

The while loop repeats a group of statements an indefinite number of times

under control of a logical condition. A matching end delineates the statements.

The general form of a while loop is:

while expression



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

The while loop

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

function whiledem(a)


while 2^n<=a




Using of this programm

>> whiledem(1)

n = 1

>> whiledem(3)

n = 2

  • Login