You are on page 1of 16

MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬

‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

FUNCTIONS
1- FUNCTIONS

A function is a group of statements that together perform a task. In


MATLAB, functions are defined in separate files. The name of the file and of the
function should be the same.

Functions operate on variables within their own workspace, which is also called
the local workspace, separate from the workspace you access at the MATLAB
command prompt which is called the base workspace.

Functions can accept more than one input arguments and may return more than one
output arguments

Function Definition Line

The first executable line in a function file must be the function definition line.

Otherwise the file is considered a script file. The function definition line:

• Defines the file as a function file.

• Defines the name of the function.

• Defines the number and order of the input and output arguments.

The form of the function definition line is:

The word “function,” typed in lowercase letters, must be the first word in
the function definition line. On the screen the word function appears in blue. The
function name is typed following the equal sign. The name can be made up of
1
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

letters, digits, and the underscore character (the name cannot include a space). The
rules for the name are the same as the rules for naming variables described in
Section 1.6.2. It is good practice to avoid names of built-in functions and names of
variables already defined by the user or predefined by MATLAB

Input and Output Arguments

The input and output arguments are used to transfer data into and out of the
function. The input arguments are listed inside parentheses following the function
name. Usually, there is at least one input argument, although it is possible to have
a function that has no input arguments. If there are more than one, the input
arguments are separated with commas. The computer code that performs the
calculations within the function file is written in terms of the input arguments and
assumes that the arguments have assigned numerical values. This means that the
mathematical expressions in the function file must be written according to the
dimensions of the arguments, since the arguments can be scalars, vectors, or
arrays. The Syntax of a function statement is:

function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)

The following are examples of function definition lines with different


combinations of input and output arguments.

Function definition line Comments


function [mpay,tpay] = Three input arguments, two
loan(amount,rate,years) output arguments.
function [A] = RectArea(a,b) Two input arguments, one output
argument.
function A = RectArea(a,b) Same as above; one output
argument can be typed without
the brackets.
function [V, S] = SphereVolArea(r) One input variable, two output
variables
function trajectory(v,h,g) Three input arguments, no output
arguments.

2
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

Example

The following function named mymax should be written in a file named


mymax.m. It takes five numbers as argument and returns the maximum of the
numbers.

Create a function file, named mymax.m and type the following code in it:

function max = mymax(n1, n2, n3, n4, n5)


%This function calculates the maximum of the
% five numbers given as input
max = n1;
if(n2 > max)
max = n2;
end
if(n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
end
if(n5 > max)
max = n5;
end

The first line of a function starts with the keyword function. It gives the
name of the function and order of arguments. In our example, the mymax function
has five input arguments and one output argument.

The comment lines that come right after the function statement provide the
help text. These lines are printed when you type:

help mymax

MATLAB will execute the above statement and return the following result:

3
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

This function calculates the maximum of the

five numbers given as input

You can call the function as:

mymax(34, 78, 89, 23, 11)

MATLAB will execute the above statement and return the following result:

ans =

89

function y=chp7one(x)
y=(x.^4.*sqrt(3*x+5))./(x.^2+1).^2;

>> chp7one(6)
ans =
4.5401
>> F=chp7one(6)
F=
4.5401

4
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

2-Primary and Sub-Functions

Any function other than an anonymous function must be defined within a


file. Each function file contains a required primary function that appears first and
any number of optional sub-functions that comes after the primary function and
used by it.

Primary functions can be called from outside of the file that defines them,
either from command line or from other functions, but sub-functions cannot be
called from command line or other functions, outside the function file.

Sub-functions are visible only to the primary function and other sub-
functions within the function file that defines them.

Example

write a function named quadratic that would calculate the roots of a quadratic
equation. The function would take three inputs, the quadratic co-efficient, the
linear co-efficient and the constant term. It would return the roots.

The function file quadratic.m will contain the primary function quadratic and the
sub-function disc, which calculates the discriminant.

Create a function file quadratic.m and type the following code in it:

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


%this function returns the roots of
% a quadratic equation.
% It takes 3 input arguments
% which are the co-efficients of x2, x and the
%constant term
% It returns the roots
d = disc(a,b,c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic
5
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

function dis = disc(a,b,c)


%function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end % end of sub-function

You can call the above function from command prompt as:

quadratic(2,4,-4)

MATLAB will execute the above statement and will give the following result:

ans =

0.7321

3-Nested Functions

You can define functions within the body of another function. These are called
nested functions. A nested function contains any or all of the components of any
other function.

Nested functions are defined within the scope of another function and they share
access to the containing function's workspace.

A nested function follows the below syntax:

function x = A(p1, p2)

...

B(p2)

function y = B(p3)

...

end

...

end

6
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

Example

Rewrite the function quadratic, from previous example, however, this time the disc
function will be a nested function.

Create a function file quadratic2.m and type the following code in it:

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


function disc % nested function
d = sqrt(b^2 - 4*a*c);
end % end of function disc
disc;
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of function quadratic2

You can call the above function from command prompt as:

quadratic2(2,4,-4)

MATLAB will execute the above statement and return the following result:

ans =

0.7321

4- Private Functions

A private function is a primary function that is visible only to a limited


group of other functions. If you do not want to expose the implementation of a
function(s), you can create them as private functions.

Private functions reside in subfolders with the special name private.

They are visible only to functions in the parent folder.

7
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

Example

Rewrite the quadratic function. This time, however, the disc function calculating
the discriminant, will be a private function.

Create a subfolder named private in working directory. Store the following


function file disc.m in it:

function dis = disc(a,b,c)


%function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end % end of sub-function

Create a function quadratic3.m in your working directory and type the following
code in it:

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


%this function returns the roots of
% a quadratic equation.
% It takes 3 input arguments
% which are the co-efficients of x2, x and the
%constant term
% It returns the roots
d = disc(a,b,c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic3

You can call the above function from command prompt as:

quadratic3(2,4,-4)

MATLAB will execute the above statement and return the following result:

ans =

0.7321

8
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

5-Global Variables

Global variables can be shared by more than one function. For this, you need
to declare the variable as global in all the functions.

If you want to access that variable from the base workspace, then declare the
variable at the command line.

The global declaration must occur before the variable is actually used in a function.
It is a good practice to use capital letters for the names of global variables to
distinguish them from other variables.

Example

Create a function file named average.m and type the following code in it:

function avg = average(nums)


global TOTAL
avg = sum(nums)/TOTAL;
end

Create a script file and type the following code in it:

global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)

When you run the file, it will display the following result:

av =

35.5000

Note: The subprograms in Matlab support getting more than one variable as
output, unlike many other programming languages, as shown in the following
example.

9
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

function [ r1 , r2 , r3 ] = multi2d( b )
r1 = sum(sum(b));
r2 = max(max(b));
r3 = min(min(b));
end

Create a script file and type the following code in it:

a=randn(3);
[ r1 , r2 , r3 ] = multi2d( a )

When you run the file, it will display the following result:

r1 =

3.4734

r2 =

3.5784

r3 =

-2.2588

10
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

Elementary Mathematical Functions


MATLAB offers many predefined mathematical functions for
technical computing which contains a large set of mathematical
functions. These functions are called built-ins. Many standard
mathematical functions, such as sin(x), cos(x),tan(x), ex, ln(x), are
evaluated by the functions sin, cos, tan, exp, and log respectively in
Matlab. The following table gives a list of some commonly used
functions. earlier you write your own functions, where variables x and
y can be numbers, vectors, or matrices (all function Call using
parentheses – passing parameter to function)

Exponential functions

round(x) Rounds x to the nearest integer


floor(x) Rounds x down to nearest integer
ceil(x) Rounds x up to nearest integer
Remainder after dividing y by x (eg remainder of 17/3
rem(y,x)
is 2)
sign(x) Returns -1 if x; returns 0 if x=0; returns 1 if x>0.
rand or
Generates a random number between 0 and 1
rand(1)
exp(x) Exponential function ex
log(x) Natural logarithm function, y=ln x (where ey=x)
sqrt(x) Square root function, x−−√x
abs(x) Absolute value function, |x|

11
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

sin(x) sine function sin x


cos(x) cos function cos x
tan(x) tan function tan x
asin (x) inverse sine (arcsine)
acos (x) inverse cosine (arccos)
returns the inverse tangent (arctangent) for each
atan(x)
elementof x
max Largest elements in array
Min Smallest elements in array
Mean Average or mean value of array
sort Sort array elements in ascending or descending order
Determine whether all array elements are nonzero or
All
true
Unique Find unique elements of vector
Length Length of vector or largest array dimension
Size Array dimensions
Sum Sum of array elements
polyarea Area of polygon
std Standard deviation
Roots Polynomial roots
Polyval Polynomial evaluation
diff Differences and approximate derivatives

Note: The ceiling of x is the smallest integer which is greater than or equal to
x, while the floor of x is the largest integer less than or equal to x.

12
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

The use of some of these functions can be illustrated through the following
examples

>> sqrt(9) >> round(3.5) >> floor(3.7) >> ceil(3.2)


ans = ans = ans = ans =
3 4 3 4

>> mod(9,2) >> rem(9,2) >> fix(4.6) >> sign(-3)


ans = ans = ans = ans =
1 1 4 -1

Example:

>> log(142)

ans =

4.9558

>> log10(142)

ans =

2.1523

Note the difference between the natural logarithm log(x) and the
decimal logarithm (base10) log10(x).

13
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

mean: Average or mean value of array, mean(A) returns the mean


values of the elements along different dimensions of an array,
mean(A,dim) returns the mean values for elements along the
dimension of A specified by scalar dim. For matrices, mean(A,2) is a
column vector containing the mean value of each row.
Examples

A = [1 2 3; 3 3 6; 4 6 8; 4 7 7];
mean(A)
ans =
3.0000 4.5000 6.0000

mean(A,2)
ans =
2.0000
4.0000
6.0000
6.0000

Unique: Find unique elements of vector, unique(A) returns the same


values as in A but with no repetitions. A can be a numeric or
character array or a cell array of strings. If A is a vector or an array, b
is a vector of unique values from A. If A is a cell array of strings, b is
a cell vector of unique strings from A. The resulting vector b is sorted
in ascending order and its elements are of the same class as A.
Examples

>> A = [1 1 5 6 2 3 3 9 8 6 2 4]
A=
1 1 5 6 2 3 3 9 8 6 2 4

14
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

>> b= unique(A)
b=
1 2 3 4 5 6 8 9

 In addition to the elementary functions, MATLAB includes a


number of predefined constant values. A list of the most common
values is given in next Table

name Description
pi 3.141592653589793…
i,j The imaginary unit i, √ −1
Inf Infinity e.g. 5/0
Undefined numerical results (Not a Number),
NaN
e.g. 0/0, inf/inf, -inf/-inf

Notes:
 Only use built-in functions on the right hand side of an expression.
Reassigning the value to a built-in function can create problems.
 There are some exceptions. For example, i and j are pre-assigned
to p¡1. However,one or both of i or j are often used as loop indices.
 To avoid any possible confusion, it is suggested to use instead ii or
jj as loop indices.

15
MATLAB 2222- 2222 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم تكنولوجيا النفط‬

Example :Write a program that solves a quadratic equation by the


constitutional method using Function .If the value under the root is less
than zero, print the expression (the root is complex ).

function quadratic_equation ( a , b , c )
delta = b^2 – 4 *a * c
if delta > 0
x1 = ( - b + sqrt ( delta )) / ( 2 * a )
x2 = ( - b – sqrt ( delta )) / ( 2 * a )
elseif delta < 0
disp ( ' the root is complex ')
else
x1_2=( - b / ( 2 * a ) )
end

then write in command window

>> quadratic_equation ( 4 , 6 , 2 )
delta =
4
x1 =
-0.5000

16

You might also like