Function Handle

Advanced Functions

Stormy Attaway , in MATLAB (Fifth Edition), 2019

10.4 Uses of Function Handles

Function handles can also be created for functions other than anonymous functions, both built-in and user-defined functions. For example, the following would create a function handle for the built-in factorial function:

>> facth = @factorial;

The @ operator gets the handle of the function, which is then stored in a variable facth.

The handle could then be used to call the function, just like the handle for the anonymous functions, as in:

>> facth(5)

ans =

120

Using the function handle to call the function instead of using the name of the function does not in itself demonstrate why this is useful, so an obvious question would be why function handles are necessary for functions other than anonymous functions.

10.4.1 Function Functions

One reason for using function handles is to be able to pass functions to other functions—these are called function functions . For example, let's say we have a function that creates an x vector. The y vector is created by evaluating a function at each of the x points, and then these points are plotted.

fnfnexamp.m

function fnfnexamp(funh)

% fnfnexamp receives the handle of a function

% and plots that function of x (which is 1:.25:6)

% Format: fnfnexamp(function handle)

x = 1:.25:6;

y = funh(x);

plot(x,y,'ko')

xlabel('x')

ylabel('fn(x)')

title(func2str(funh))

end

What we want to do is pass a function to be the value of the input argument funh, such as sin, cos, or tan. Simply passing the name of the function does not work:

>> fnfnexamp(sin)

Error using sin

Not enough input arguments.

Instead, we have to pass the handle of the function:

>> fnfnexamp(@sin)

This creates the y vector as sin(x) and then brings up the plot as seen in Figure 10.1. The function func2str converts a function handle to a character vector; this is used for the title.

Figure 10.1

Figure 10.1. Plot of sin created by passing handle of function to plot.

Passing the handle to the cos function instead would graph cosine instead of sine:

>> fnfnexamp(@cos)

We could also pass the handle of any user-defined or anonymous function to the fnfnexamp function. Note that if a variable stores a function handle, just the name of the variable would be passed (not the @ operator). For example, for our anonymous function defined previously,

>> fnfnexamp(cirarea)

The function func2str will return the definition of an anonymous function as a character vector that could also be used as a title. For example:

>> cirarea = @ (radius) pi ⁎ radius .ˆ 2;

>> fnname = func2str(cirarea)

fnname =

@(radius)pi⁎radius.ˆ2

There is also a built-in function str2func that will convert a string scalar or character vector to a function handle. A string containing the name of a function could be passed as an input argument, and then converted to a function handle.

fnstrfn.m

function fnstrfn(funstr)

% fnstrfn receives the name of a function as a string

% it converts this to a function handle and

% then plots the function of x (which is 1:.25:6)

% Format: fnstrfn(function name as string)

x = 1:.25:6;

funh = str2func(funstr);

y = funh(x);

plot(x,y,'ko')

xlabel('x')

ylabel('fn(x)')

title(funstr)

end

This would be called by passing a string to the function and would create the same plot as in Figure 10.1:

>> fnstrfn("sin")

Practice 10.3

Write a function that will receive as input arguments an x vector and a function handle and will create a vector y that is the function of x (whichever function handle is passed) and will also plot the data from the x and y vectors with the function name in the title.

MATLAB has some built-in function functions. One built-in function function is fplot, which plots a function between limits that are specified. The form of the call to fplot is:

fplot(fnhandle, [xmin, xmax])

For example, to pass the sin function to fplot, one would pass its handle (see Figure 10.2 for the result).

Figure 10.2

Figure 10.2. Plot of sin created using fplot.

>> fplot(@sin, [-pi, pi])

The fplot function is a nice shortcut—it is not necessary to create x and y vectors, and it plots a continuous curve rather than discrete points.

Quick Question!

Could you pass an anonymous function to the fplot function?

Answer:

Yes, as in:

>> cirarea = @ (radius) pi ⁎ radius .ˆ 2;

>> fplot(cirarea, [1, 5])

>> title(func2str(cirarea))

Note that, in this case, the @ operator is not used in the call to fplot, as cirarea already stores the function handle.

The function function feval will evaluate a function handle and execute the function for the specified argument. For example, the following is equivalent to sin(3.2):

>> feval(@sin, 3.2)

ans =

-0.0584

Another built-in function function is fzero, which finds a zero of a function near a specified value. For example:

>> fzero(@cos,4)

ans =

4.7124

10.4.2 Timing Functions

The function timeit (introduced in R2013b) can be used to time functions and is more robust than using tic and toc. The timeit function takes one input argument, which is a function handle; this can be the handle of any type of function. The time is returned in seconds.

>> fh = @() prod(1:10000000);

>> timeit(fh)

ans =

0.0308

A warning message is thrown if the function is too fast.

>> fh = @() prod(1:100);

>> timeit(fh)

Warning: The measured time for F may be inaccurate because it is running too fast. Try measuring something that takes longer.

> In timeit (line 158)

ans =

1.3993e-06

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780128154793000106

Introduction to GPU programming in MATLAB

Nikolaos Ploskas , Nikolaos Samaras , in GPU Programming in MATLAB, 2016

4.3 Built-in MATLAB Functions for GPUs

As of MATLAB R2015b, the functions presented in Table 4.3 and their symbol operators are enhanced to accept gpuArray input arguments so that they execute on the GPU.

Table 4.3. Built-in MATLAB functions for GPUs

Function Function Function Function
abs edge interp2 qmr
accumarray eig interp3 qr
acos end interpn quiver
acosd eps interpstreamspeed quiver3
acosh eq intersect rad2deg
acot erf inv radon
acotd erfc ipermute rdivide
acoth erfcinv iradon real
acsc erfcx isaUnderlying reallog
acscd erfinv isbanded realpow
acsch errorbar isdiag realsqrt
all existsOnGPU isempty reducepatch
and exp isequal reducevolume
angle expm isequaln regionprops
any expm1 isequalwithequalnans rem
applylut ezcontour isfinite repmat
area ezcontourf isfloat reshape
arrayfun ezgraph3 ishermitian rgb2gray
asec ezmesh isinf rgb2hsv
asecd ezmeshc isinteger rgb2ycbcr
asech ezplot islogical ribbon
asin ezplot3 ismember roots
asind ezpolar isnan rose
asinh ezsurf isnumeric rot90
assert ezsurfc isocaps round
atan factorial isocolors scatter3
atan2 feather isonormals sec
atan2d fft isosurface secd
atand fft2 isreal sech
atanh fftfilt issorted semilogx
bandwidth fftn issparse semilogy
bar fill issymmetric setdiff
bar3 fill3 istril setxor
bar3h filter istriu shiftdim
barh filter2 ldivide shrinkfaces
besselj find le sign
bessely fix legendre sin
beta flip length sind
betainc flipdim line single
betaincinv fliplr log sinh
betaln flipud log10 size
bicg floor log1p slice
bicgstab fplot log2 smooth3
bicgstabl fprintf logical sort
bitand full loglog sortrows
bitcmp gamma lsqr sparse
bitget gammainc lt spfun
bitor gammaincinv lu spones
bitset gammaln mat2gray sprintf
bitshift gather mat2str spy
bitxor ge max sqrt
bsxfun gmres mean stairs
bwdist gpuArray medfilt2 std2
bwlabel gradient mesh stdfilt
bwlookup gt meshc stem
bwmorph hist meshgrid stem3
cast histc meshz stream2
cat histcounts min stream3
cconv histeq minres streamline
cdf2rdf histogram minus streamparticles
ceil horzcat mldivide streamribbon
cgs hsv2rgb mod streamslice
chol hypot mode streamtube
circshift idivide mpower stretchlim
clabel ifft mrdivide sub2ind
classUnderlying ifft2 mtimes subsasgn
comet ifftn ndgrid subsindex
comet3 im2double ndims subspace
compass im2int16 ne subsref
complex im2single nextpow2 subvolume
cond im2uint16 nnz sum
coneplot im2uint8 nonzeros superiorfloat
conj imabsdiff norm surf
contour imadjust normest surfc
contour3 imag normxcorr2 surfl
contourc image not svd
contourf imagesc nthroot swapbytes
contourslice imbothat null symmlq
conv imclose num2str tan
conv2 imcomplement numel tand
convn imdilate nzmax tanh
corr2 imerode or tfqmr
corrcoef imfill orth times
cos imfilter padarray transpose
cosd imgaussfilt pagefun trapz
cosh imgaussfilt3 pareto tril
cot imgradient patch trimesh
cotd imgradientxy pcg trisurf
coth imhist pcolor triu
cov imlincomb permute typecast
csc imnoise pie uint16
cscd imopen pie3 uint32
csch imreconstruct planerot uint64
ctranspose imregdemons plot uint8
cummax imregionalmax plot3 uminus
cummin imregionalmin plotmatrix union
cumprod imresize plotyy unique
cumsum imrotate plus unwrap
curl imrotate_old polar uplus
deg2rad imshow poly var
del2 imtophat polyder vertcat
det ind2sub polyfit vissuite
diag inpolygon polyval volumebounds
diff int16 polyvalm voronoi
disp int2str pow2 waterfall
display int32 power xcorr
divergence int64 prod xor
dot int8 psi ycbcr2rgb
double interp1

To get a complete list of the GPU-enabled functions in any release, type methods('gpuArray'). Moreover, you can display the documentation of these functions by typing help gpuArray/functionname, for example, help gpuArray/fft (Fig. 4.10).

Fig. 4.10. Display documentation of GPU-enabled functions.

Whenever any of these functions is called with at least one gpuArray as an input argument, the function executes on the GPU and generates a gpuArray as the result. You can mix inputs using both gpuArray and MATLAB arrays in the same function call; the MATLAB arrays are automatically transferred to the GPU for the function execution. For example, the following code creates array A directly on the GPU and array B on the MATLAB workspace. When calling the mtimes function (matrix multiplication) with those two input arguments, MATLAB automatically transfers array B on the GPU and performs the matrix multiplication on the GPU (Fig. 4.11).

Fig. 4.11. Mixing inputs using gpuArray and MATLAB arrays.

The following code uses the fft function along with the arithmetic operator *. All calculations are performed on the GPU. Function gather retrieves the data from the GPU back to the MATLAB workspace (Fig. 4.12).

Fig. 4.12. gpuArray objects and arrays on the MATLAB workspace.

To measure the performance of a code running on the GPU, there are two options:

gputimeit : This function takes as input a function handle with no input arguments and returns the execution time of that function. It takes care of benchmarking considerations like repeating the timed operation to get more accurate results, executing the function before measurement to avoid initialization overhead and subtracting out the overhead of the timing function. Also, gputimeit ensures that all operations on the GPU have completed before the final timing. For example, the following code measures the execution time to compute the fft of a 1, 000 × 1, 000 random matrix (Fig. 4.13):

Fig. 4.13. Measuring the execution time of a built-in function using gputimeit.

If you want to measure a custom function, you can use gputimeit in a similar way. For example, let's assume that we want to measure the execution time of the custom function myFun that takes as input arguments two arrays of the same size (Fig. 4.14):

Fig. 4.14. Measuring the execution time of a custom function using gputimeit.

tic and toc: We can use tic and toc to measure the execution time. However, to get accurate timing on the GPU, you must wait for operations to complete before calling toc. There are two ways to do this. You can call gather on the final GPU output before calling toc because this function forces all computations to complete before the time measurement is taken. Alternately, you can use the wait function with a GPUDevice object as its input. For example, the following code measures the execution time to compute the fft of a 1, 000 × 1, 000 random matrix (Fig. 4.15):

Fig. 4.15. Measuring the execution time of a built-in function using tic and toc.

If you want to measure a custom function, you can also use tic and toc in a similar way. For example, let's assume that we want to measure the execution time of the custom function myFun that takes as input arguments two arrays of the same size (Fig. 4.16):

Fig. 4.16. Measuring the execution time of a custom function using tic and toc.

As of MATLAB R2015b, there are only a few functions that support sparse gpuArray objects. Whenever possible, you should use sparse gpuArray objects on your calculations because it will improve your code's performance in cases when your data are sparse. Table 4.4 presents the functions that support sparse gpuArray objects:

Table 4.4. MATLAB functions supporting sparse gpuArray objects

Function Function Function Function
abs gmres length realsqrt
angle gpuArray.speye log1p round
ceil imag minus sign
classUnderlying isaUnderlying mtimes size
conj isempty ndims sparse
ctranspose isequal nextpow2 spfun
deg2rad isequaln nnz spones
end isfloat nonzeros sqrt
expm1 isinteger numel sum
find islogical nzmax transpose
fix isnumeric plus uminus
floor isreal rad2deg uplus
full issparse real

You can create a sparse gpuArray either by calling sparse with a gpuArray input, or by calling gpuArray with a sparse input (Fig. 4.17):

Fig. 4.17. Creating sparse gpuArray objects.

For example, the following code creates two random sparse arrays, transfers them to the GPU, and performs some basic matrix operations (addition, subtraction, multiplication, and transpose). All the calculations are performed on the GPU (Fig. 4.18):

Fig. 4.18. Calculations on sparse gpuArray objects.

If the output of a function running on the GPU could potentially be complex, you must explicitly specify its input arguments as complex. This applies to gpuArray or to functions called in code run by arrayfun (see Section 4.4). As of MATLAB R2015b, Table 4.5 presents the functions that might return complex data, along with the input range over which the output remains real.

Table 4.5. MATLAB functions that might return complex data

Function Input range for real output
acos(x) x 1
acosd(x) x 1
acosh(x) x ≥ 1
acot(x) x R
acotd(x) x R
acoth(x) x 1
acsc(x) x 1
acscd(x) x 1
acsch(x) x R
asec(x) x 1
asecd(x) x 1
asech(x) 0 ≤ x ≤ 1
asin(x) x 1
asind(x) x 1
asinh(x) x R
atan(x) x R
atand(x) x R
atanh x 1
cos(x) For purely real values or imaginary values of x
cosd(x) For purely real values or imaginary values of x
cosh(x) For purely real values or imaginary values of x
cot(x) x R
cotd(x) x R
coth(x) x R
csc(x) x R
cscd(x) x R
csch(x) x R
log(x) x ≥ 0
log1p(x) x ≥−1
log10(x) x ≥ 0
log2(x) x ≥ 0
power(x,y) x ≥ 0
reallog(x) x ≥ 0
realsqrt(x) x ≥ 0
sin(x) x R
sind(x) x R
sinh(x) x R
sqrt(x) x ≥ 0
tan(x) x R
tand(x) x R
tanh(x) x R

For example, if creating a gpuArray that might have negative elements, use B = gpuArray(complex(A));. Then you can successfully execute sqrt(B). Otherwise, sqrt(B) will generate an error (Fig. 4.19):

Fig. 4.19. Explicitly specify complex input arguments.

Example: Image edge detection

Edge detection is a common operation on images. It is a method of tracking discontinuities within the image pixels. These discontinuities may exist due to the morphology of the objects in the image, to shadows, or may be abrupt changes in colors. A simple and efficient way of finding edges is image filtering. Spatial time invariant filtering is achieved by convolving the original signal (in this case the 2-D discrete image signal) with the filter kernel. The filter kernel is a matrix that assigns weights to the terms of the convolution sum.

In the following example, we partially use the steps of the Canny Edge Detector to track image edges. The steps used are as follows:

(1)

Convert the image to grayscale.

(2)

Smooth the image with Gaussian noise, using a 25 × 25 Gaussian kernel filter.

(3)

Calculate the derivatives of the image in horizontal and vertical axes, accordingly, for each pixel. In this example, the 3 × 3 and 9 × 9 Sobel kernels are used.

(4)

Normalize the values from step 3.

(5)

Calculate the magnitude of the derivative (edge strength) in every pixel ignoring edge direction.

(6)

Suppress all values that are below a certain threshold.

Function edgeDetection (filename: edgeDetection.m) is used to illustrate the above example in MATLAB.

Initially, we measure the execution time of this function running on the CPU using a 5, 789 × 3, 867 jpeg image:

To execute this function on the GPU, we do not have to perform any changes to the code because all functions and operators used are GPU-enabled. The only difference is that we should pass a gpuArray as input to that function. We measure the execution time of this function running on the GPU using the same image:

Hence, the image edge detection function is running ∼9.25 × faster on the GPU.

Fig. 4.20 shows the result of the image edge detection function in case of a 3 × 3 and 9 × 9 Sobel filter.

Fig. 4.20. Result of the image edge detection function.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780128051320000047

Geeks and Luddites: library culture and communication

Dan Gall , Donna Hirst , in An Overview of the Changing Role of the Systems Librarian, 2010

Systems librarian as hardware guru

When computers were introduced into libraries, the systems staff learned the technology 'on the fly.' Systems staff became conversant with DOS and later Pascal and still later C. The systems librarian learned network and hardware details. Lavagnino (1997: 218, 220) indicates:

The systems librarian . . . was concerned with mainframe and minicomputer systems development and implementation, and usually was found working for bibliographic utilities, vendors, or large university libraries developing in-house systems. The systems generally were developed to handle functions used by staff, such as circulation or acquisitions; few public services functions were automated. These systems librarians dealt mostly with technical issues such as setting terminal characteristics, managing appropriate inputs and outputs to and from the system, running indexing jobs, and backing up the system. This involved interacting with programmers in developing the system and with technicians in keeping it running, and sometimes in operating the system and training library staff. These early systems librarians did not interact with the public, the college or university students, staff, and faculty but instead were limited to working with library and computer center staff and faculty.

As libraries (and the culture at large) became more and more dependent on technology, the geeks and hardware gurus held the power to aid library staff charged with maintaining the day-to-day workflow of the libraries. Frequently the technical staff began to talk a special techno- speak while the general library staff believed that these technicians no longer knew how to speak English. Often the library staff became distrustful of the systems librarians. Several articles highlight this tension between library staff and library technologists including Davidson and Rusk (1996: 302–5), reporting that differences in underlying values and styles of librarians and technologists created difficulties in reaching consensus.

It's 1975. Annie AlphaGeek is the lady with the magic fingers. She can fix barcode scanners and test new network connections, while assisting the staff with their problems. Larry Luddite is able to continue to avoid most library technology and when required to use the circulation system he is so inept that he is not asked to assist with this work again.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B978184334598550004X

Buffer Overflow

In Hack Proofing Your Network (Second Edition), 2002

Stack Frames and Calling Syntaxes

There are numerous ways that functions can be called, and it makes a difference as to how the stack is laid out. Sometimes it is the caller's responsibility to clean up the stack after the function returns, other times the called function handles this. The type of call tells the compiler how to generate code, and it affects the way we must look at the stack frame itself.

The most common calling syntax is C declaration syntax. A C-declared function is one in which the arguments are passed to a function on the stack in reverse order (with the first argument being pushed onto the stack last). This makes things easier on the called function, because it can pop the first argument off the stack first. When a function returns, it is up to the caller to clean up the stack based on the number of arguments it pushed earlier. This allows a variable number of arguments to be passed to a function, which is the default behavior for MS Visual C/C++ generated code and the most widely-used calling syntax on many other platforms. This is sometimes known as cdecl calling syntax. A function that uses this call syntax is printf(), because a variable number of arguments can be passed to the printf function and printf handles them. After that, the caller cleans up after itself.

The next most common calling syntax is the standard call syntax. Like the cdecl, arguments are passed to functions in reverse order on the stack. However, unlike cdecl calling syntax, it is up to the called function to readjust the stack pointers before returning. This is useful because it frees the caller from having to worry about this, and it can also save some code space as the code to readjust the stack is only in the function rather than residing everywhere the function is called. Almost the entire WIN32 API is written using the standard call syntax. It is sometimes known as stdcall.

The third type of calling syntax is called fast call syntax. It is very similar to standard call syntax in that it is up to the called function to clean up after itself. It differs from standard call syntax, however, in the way arguments are passed to the stack. Fast call syntax states that the first two arguments to a function are passed directly in registers, meaning that they are not required to be pushed onto the stack and the called function can reference them directly using the registers in which they were passed. Delphi-generated code tends to use fast call syntax, and it is also a common syntax in the NT kernel space.

Finally, there is one last calling syntax, called naked. In reality, this is the opposite of a calling syntax, as it removes all code designed to deal with calling syntaxes in a function and forces the function's programmer to deal with the details. Naked is rarely used, and when it is used, it's typically for a very good reason (such as supporting a very old piece of binary code).

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9781928994701500112

Selecting Best Features for Predicting Bank Loan Default

Zahra Yazdani , ... Babak Teimourpour , in Data Mining Applications with R, 2014

8.5.2 Data Set Balancing

Most of data sets in the real world have unbalanced class distributions that cause some problems in classification models. Most learning algorithms tend to omit the smaller class because it is not supported statistically. Hence the accuracy will rise unrealistically. We sampled train and test data sets from all available objects randomly and used the SMOTE function of package DMwR for the training data to overcome these problems. The test set included around 500 observations and the balanced train set contained around 1500 observations.

The SMOTE function handles unbalanced classification problems using the SMOTE method. Namely, it can generate a new "SMOTEd" data set that addresses the class unbalance problem. It generates new examples of minority classes artificially using the nearest neighbors of this class of elements and under samples the majority class to balance the training data set ( Torgo, 2011). The following code is used for balancing the training data set:

library(DMwR)

attach(mydata)

tr<−sample(nrow(m), round(nrow(mydata)*0.7))

train=mydata[tr,]

test=mydata[−   tr,]

data_smot=train

data_smot$defn <− factor(ifelse(data_smot$defn == 1, "def", "nondef"))

data_samp <− SMOTE(defn ~ ., data_smot, k=5,perc.over = 500)

Figure 8.6 shows the data distribution before and after balancing. To represent the data distribution in two statuses, we utilized the Multi Dimensional Scaling (MDS) method.

Figure 8.6. Data class distribution before and after balancing.

MDS is a method based on proximities between objects, subjects, or stimuli used to produce a spatial representation of these items. Proximities express the similarity or dissimilarity between data objects (Härdle and Simar, 2006). It represents the objects as the points such that the distances between them are nearly proximities between same objects. To plot objects in two dimensional space, the following code can be used:

library(cluster)

dist=daisy(data_samp[,-19],stand=TRUE,metric=c("gower"),

type=list(interval=c(1,5,6,7,11,13,14),

ratio=c(7,8,17,18), nominal=c(2,12),

binary=c(3,4,10,15,16))),11,15,16)))

loc=cmdscale(d,k=2)

x=loc[,1]

y=loc[,2]

plot(x,y,type="n")

text(x,y,labels=as.expression(as.numeric(data_samp[,19])),col=as.numeric(data_samp[,19]))

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780124115118000086

Advanced Plotting Techniques

Stormy Attaway , in MATLAB (Fifth Edition), 2019

12.4.1 Plotting From a Function

The following function generates a Figure Window (seen in Figure 12.28) that shows different types of plots for the same data. The data are passed as input arguments (as an x vector and the handle of a function to create the y vector) to the function, as is a cell array with the plot type names. The function generates the Figure Window using the cell array with the plot type names. It creates a function handle for each using the str2func function.

Figure 12.28

Figure 12.28. Subplot showing different file types with their names as titles.

plotxywithcell.m

function plotxywithcell(x, fnhan, rca)

% plotxywithcell receives an x vector, the handle

% of a function (used to create a y vector), and

% a cell array with plot type names; it creates

% a subplot to show all of these plot types

% Format: plotxywithcell(x,fn handle, cell array)

lenrca = length(rca);

y = fnhan(x);

for i = 1:lenrca

subplot(1,lenrca,i)

funh = str2func(rca{i});

funh(x,y)

title(upper(rca{i}))

xlabel('x')

ylabel(func2str(fnhan))

end

end

For example, the function could be called as follows:

>> anfn = @ (x) x .ˆ 3;

>> x = 1:2:9;

>> rca = {'bar', 'area', 'plot'};

>> plotxywithcell(x, anfn, rca)

The function is general and works for any number of plot types stored in the cell array.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B978012815479300012X

Advanced Mathematics

Stormy Attaway , in MATLAB (Fifth Edition), 2019

14.7.1 Integration and the Trapezoidal Rule

The integral of a function f(x) between the limits given by x = a and x = b is written as

a b f x dx

and is defined as the area under the curve f(x) from a to b, as long as the function is above the x-axis. Numerical integration techniques involve approximating this.

One simple method of approximating the area under a curve is to draw a straight line from f(a) to f(b) and calculate the area of the resulting trapezoid as

b a f a + f b 2

In MATLAB, this could be implemented as a function.

An improvement on this is to divide the range from a to b into n intervals, apply the trapezoidal rule to each interval, and sum them. For example, for the preceding if there are two intervals, you would draw a straight line from f(a) to f((a   +   b)/2) and then from f((a   +   b)/2) to f(b).

The Programming Concept

Here is a function to which the function handle and limits a and b are passed:

trapint.m

function int = trapint(fnh, a, b)

% trapint approximates area under a curve f(x)

%   from a to b using a trapezoid

% Format: trapint(handle of f, a, b)

int = (b-a) ⁎ (fnh(a) + fnh(b))/2;

end

To call it, for example, for the function f(x) = 3x2 − 1, an anonymous function is defined and its handle is passed to the trapint function.

>> f = @ (x) 3 ⁎ x .ˆ 2 - 1;

approxint = trapint(f, 2, 4)

approxint =

58

The Efficient Method

MATLAB has a built-in function trapz that will implement the trapezoidal rule. Vectors with the values of x and y = f(x) are passed to it. For example, using the anonymous function defined previously:

>> x = [2 4];

>> y = f(x);

>> trapz(x,y)

ans =

58

The Programming Concept

The following is a modification of the previous function to which the function handle, limits, and the number of intervals are passed:

trapintn.m

function intsum = trapintn(fnh, lowrange,highrange, n)

% trapintn approximates area under a curve f(x) from

%   a to b using trapezoids with n intervals

% Format: trapintn(handle of f, a, b, n)

intsum = 0;

increm = (highrange - lowrange)/n;

for a = lowrange: increm : highrange - increm

b = a + increm;

intsum = intsum + (b-a) ⁎ (fnh(a) + fnh(b))/2;

end

end

For example, this approximates the integral of the previous function f with two intervals:

>> trapintn(f,2,4,2)

ans =

55

In these examples, straight lines, which are first-order polynomials, were used. Other methods involve higher-order polynomials. The built-in function quad uses Simpson's method. Three arguments are normally passed to it: the handle of the function, and the limits a and b. For example, for the previous function:

>> quad(f,2,4)

ans =

54

The Efficient Method

To use the built-in function trapz to accomplish the same thing, the x vector is created with the values 2, 3, and 4:

>> x = 2:4;

>> y = f(x)

>> trapz(x,y)

ans =

55

MATLAB has a function polyint, which will find the integral of a polynomial. For example, for the polynomial 3x 2 + 4x4, which would be represented by the vector [3 4 -4], the integral is found by:

>> origp = [3 4 -4];

>> intp = polyint(origp)

intp =

1   2   -4   0

which shows that the integral is the polynomial x 3 + 2x 2 4x.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780128154793000143

Convergence of IP and Optical Networking

Kristin Rauschenbach , Cesar Santivanez , in Optical Fiber Telecommunications (Sixth Edition), 2013

16.3.3 Control plane functions

While the definition of a control plane continues to evolve, in general, the control plane serves to decouple services from service delivery mechanisms and to decouple quality-of-service from its realization mechanisms. It also provides boundaries for policy and information sharing based on trust, business models, and need for scale. It provides end-to-end signaling path and maintains topology and path information across heterogeneous platforms.

A typical control plane handles functions of network element discovery, routing, path computation, and signaling and connection setup. Discovery is the process of learning the links and nodes that are adjacent to a given node. Discovery protocols manage the finding and verification of nodes and links, including real-time updates for liveliness. Discovery is enabled by exchanging address or naming information over either the in-band or out-of-band control channel.

Routing is the process of establishing all link and node connectivity in the network topology, the reachability of a node to other nodes in the network, and resource information such as link bandwidth and node switching capacity and connectivity. The routing information is used to construct a full network topology of the available links and nodes in the network, and is either stored locally in the network elements, maintained in management database, or in some combination of these. The management of the topology information database, including where the information is stored, how it is updated, and how it is used for network optimization and service creation, drives the control and management plane architecture and implementation. In today's optical networks routing information is typically gathered infrequently, as network topology does not change frequently. In contrast, in IP networks, routing is handled on a packet-by-packet basis.

To achieve scale, not all resource information is included in the routing protocol. Abstraction, or minimal resource representation, is used to filter information and help scale, albeit at the sacrifice of optimization potential. Path computation provides available source-destination paths to either the endpoints or the traffic-engineering engine in the network. Path computation takes in routing information, and adds other optimization features, such as cost functions, desired protection schemes, or diverse routing requirements to determine viable network paths.

Signaling serves to implement a desired path setup or tear-down, as well as maintaining liveness information of an active path.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B978012396960600016X

Session Management and Mobility

Magnus Olsson , ... Catherine Mulligan , in EPC and 4G Packet Networks (Second Edition), 2013

6.2.2.5 Bearers in PMIP- and GTP-Based Deployments

In the illustration for bearers in GTP-based systems above, the EPS bearers extend between the UE and the PDN GW. This is how it works when GTP is used between Serving GW and PDN GW. As explained in Chapter 2, it is also possible to deploy EPS with PMIP between Serving GW and PDN GW. While GTP is designed to support all functionality required to handle the bearer signaling, as well as the user-plane transport, PMIP was designed by IETF to only handle functions for mobility and forwarding of the user plane. PMIP thus had no built-in features to bearers or QoS-related signaling. During 2007 there were long discussions in 3GPP whether PMIP should be extended to support bearer-related signaling, as well as to allow user-plane marking to identify the EPS bearers, similar to GTP. It was eventually decided, however, that the PMIP-based reference points would not be aware of the EPS bearers. This means that it is not possible for the bearers to extend all the way between UE and PDN GW. Instead, the bearers are only defined between UE and Serving GW when PMIP-based S5/S8 is used. Consequently, it is not sufficient to have the packet filters only in UE and PDN GW. Without bearer markings between S-GW and PDN GW, also the Serving GW would need to know the packet filters in order to map the downlink traffic onto the appropriate bearer towards the UE. This is illustrated in Figure 6.10.

Figure 6.10. EPS Bearer When PMIP-based S5/S8 Is Used.

The observant reader will have noticed from Figure 6.10 that the PDN GW still uses the packet filters, just as with the GTP-based S5/S8. Why is this so? Isn't it enough that the Serving GW has the packet filters in this case? It is true that the PDN GW does not need the packet filters to do the bearer mapping of downlink traffic, since this is instead done by the Serving GW when PMIP-based S5/S8 is used. The PDN GW, however, still performs important functionality such as bit rate enforcement and charging for the different IP flows. This is not directly related to the EPS bearers but it is the reason why the PDN GW also has packet filter knowledge for PMIP-based S5/S8. These functions of the PDN GW, common to both PMIP-based S5/S8 and GTP-based S5/S8, are further described in Section 8.2 on PCC.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780123945952000062

Functions

Qingkai Kong , ... Alexandre M. Bayen , in Python Programming and Numerical Methods, 2021

3.6 Summary and Problems

3.6.1 Summary

1.

A function is a self-contained set of instructions designed to perform a specific task.

2.

A function has its own memory block for its variables. Information can be added to a function's memory block only through a function's input variables. Information can leave the function's memory block only through a function's output variables.

3.

A function can be defined within another function, which is called a nested function. This nested function can be only accessed by the parent function.

4.

You can define an anonymous function using the keyword lambda, which is the so-called lambda function.

5.

You can assign functions to variables using function handles.

3.6.2 Problems

1.

Recall that the hyperbolic sine, denoted by sinh, is exp ( x ) exp ( x ) 2 . Write a function my_sinh(x) where the output y is the hyperbolic sine computed on x. Assume that x is a 1 by 1 float.

Test Cases:

2.

Write a function my_checker_board(n) where the output m is an n × n array with the following form:

m = 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

Note that the upper-left element should always be 1. Assume that n is a strictly positive integer.

Test Cases:

3.

Write a function my_triangle(b,h) where the output is the area of a triangle with base, b, and height, h. Recall that the area of a triangle is one-half the base times the height. Assume that b and h are just 1 by 1 float numbers.

Test Cases:

4.

Write a function my_split_matrix(m), where m is an array, the output is a list [m1, m2] where m1 is the left half of m, and m2 is the right half of m. In the case where there is an odd number of columns, the middle column should go to m1. Assume that m has at least two columns.

Test Cases:

5.

Write a function my_cylinder(r,h), where r and h are the radius and height of a cylinder, respectively, and the output is a list [s, v] where s and v are the surface area and volume of the same cylinder, respectively. Recall that the surface area of a cylinder is 2 π r 2 + 2 π r h , and the volume is π r 2 h . Assume that r and h are 1 by 1 floats.

Test Cases:

6.

Write a function my_n_odds(a), where a is a one-dimensional array of floats and the output is the number of odd numbers in a.

Test Cases:

7.

Write a function my_twos(m,n) where the output is an m × n array of twos. Assume that m and n are strictly positive integers.

Test Cases:

8.

Write a lambda function that takes in input x and y, and the output is the value of x - y.

9.

Write a function add_string(s1, s2) where the output is the concatenation of the strings s1 and s2.

Test Cases:

10.

Generate the following errors:

TypeError: fun() missing 1 required positional argument: "a"

IndentationError: expected an indented block

11.

Write a function greeting(name, age) where name is a string, age is a float, and the output is a string "Hi, my name is XXX and I am XXX years old." where XXX are the input name and age, respectively.

Test Cases:

12.

Let r1 and r2 be the radius of circles with the same center and let r2   >   r1. Write a function my_donut_area(r1, r2) where the output is the area outside of the circle with radius r1 and inside the circle with radius r2. Make sure that the function is vectorized. Assume that r1 and r2 are one-dimensional arrays of the same size.

Test Cases:

13.

Write a function my_within_tolerance(A, a, tol) where the output is an array or list of the indices in A such that | A a | < tol . Assume that A is a one-dimensional float list or array, and that a and tol are 1 by 1 floats.

Test Cases:

14.

Write a function bounding_array(A, top, bottom) where the output is equal to the array A wherever bottom < A < top, the output is equal to bottom wherever A <= bottom, and the output is equal to top wherever A >= top. Assume that A is a one-dimensional float array and that top and bottom are 1 by 1 floats.

Test Cases:

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780128195499000129