CHAPTER 6

image

Numerical Calclus with MATLAB. Applications to Differential Equations

MATLAB and Programming

MATLAB can be used as a high-level programming language including data structures, functions, instructions for flow control, management of inputs/outputs and even object-oriented programming.

MATLAB programs are usually written in files called M-files. An M-file is nothing more than a MATLAB code (script) that executes a series of commands or functions that accept arguments and produce an output. The M-files are created using the text editor.

Text Editor

The Editor/Debugger is activated by clicking on the create a new M-file button 9781484203118_unFig06-01.jpg in the MATLAB desktop or by selecting File image New image M-file in the MATLAB desktop (Figure 6-1) or Command Window (Figure 6-2). The Editor/Debugger opens a file in which we create the M-file, i.e. a blank file into which we will write MATLAB programming code (Figure 6-3). You can open an existing M-file using File image Open on the MATLAB desktop (Figure 6-1) or, alternatively, you can use the command Open in the Command Window (Figure 6-2). You can also open the Editor/Debugger by right-clicking on the Current Directory window and choosing New image M-file from the resulting pop-up menu (Figure 6-4). Using the menu option Open, you can open an existing M-file. You can open several M-files simultaneously, each of which will appear in a different window.

Figure 6-5 shows the functions of the icons in the Editor/Debugger.

Scripts

Scripts are the simplest possible M-files. A script has no input or output arguments. It simply consists of instructions that MATLAB executes sequentially and that could also be submitted in a sequence in the Command Window. Scripts operate with existing data on the workspace or new data created by the script. Any variable that is used by a script will remain in the workspace and can be used in further calculations after the end of the script.

Below is an example of a script that generates several curves in polar form, representing flower petals. Once the syntax of the script has been entered into the editor (Figure 6-6), it is stored in the work library (work) and simultaneously executes by clicking the button 9781484203118_unFig06-01.jpg or by selecting the option Save and run from the Debug menu (or pressing F5). To move from one chart to the next press ENTER.

9781484203118_Fig06-07.jpg

Figure 6-7.

9781484203118_Fig06-08.jpg

Figure 6-8.

9781484203118_Fig06-09.jpg

Figure 6-9.

9781484203118_Fig06-10.jpg

Figure 6-10.

Functions and M-Files. Function, Eval and Feval

We already know that MATLAB has a wide variety of functions that can be used in everyday work with the program. But, in addition, the program also offers the possibility of custom defined functions. The most common way to define a function is to write its definition to a text file, called an M-file, which will be permanent and will therefore enable the function to be used whenever required.

MATLAB is usually used in command mode (or interactive mode), in which case a command is written in a single line in the Command Window and is immediately processed. But MATLAB also allows the implementation of sets of commands in batch mode, in which case a sequence of commands can be submitted which were previously written in a file. This file (M-file) must be stored on disk with the extension “.m” in the MATLAB subdirectory, using any ASCII editor or by selecting M-file New from the File menu in the top menu bar, which opens a text editor that will allow you to write command lines and save the file with a given name. Selecting M-File Open from the File menu in the top menu bar allows you to edit any pre-existing M-file.

To run an M-file simply type its name (without extension) in interactive mode into the Command Window and press Enter. MATLAB sequentially interprets all commands and statements of the M-file line by line and executes them. Normally the literal commands that MATLAB is performing do not appear on screen, except when the command echo on is active and only the results of successive executions of the interpreted commands are displayed. Normally, work in batch mode is useful when automating large scale tedious processes which, if done manually, would be prone to mistakes. You can enter explanatory text and comments into M-files by starting each line of the comment with the symbol %. The help command can be used to display comments made in a particular M-file.

The command function allows the definition of functions in MATLAB, making it one of the most useful applications of M-files. The syntax of this command is as follows:

function output_parameters = function_name (input_parameters)
the function body

Once the function has been defined, it is stored in an M-file for later use. It is also useful to enter some explanatory text in the syntax of the function (using %), which can be accessed later by using the help command.

When there is more than one output parameter, they are placed between square brackets and separated by commas. If there is more than one input parameter, they are separated by commas. The body of the function is the syntax that defines it, and should include commands or instructions that assign values to output parameters. Each command or instruction of the body often appears in a line that ends either with a comma or, when variables are being defined, by a semicolon (in order to avoid duplication of outputs when executing the function). The function is stored in the M-file named function_name.m.

Let us define the function fun1(x) = x ^ 3 - 2 x + cos(x), creating the corresponding M-file fun1.m. To define this function in MATLAB select M-file New from the File menu in the top menu bar (or click the button 9781484203118_unFig06-01.jpg in the MATLAB tool bar). This opens the MATLAB Editor/Debugger text editor that will allow us to insert command lines defining the function, as shown in Figure 6-11.

To permanently save this code in MATLAB select the Save option from the File menu at the top of the MATLAB Editor/Debugger. This opens the Save dialog of Figure 6-12, which we use to save our function with the desired name and in the subdirectory indicated as a path in the file name field. Alternatively you can click on the button 9781484203118_unFig06-02.jpg or select Save and run from the Debug menu. Functions should be saved using a file name equal to the name of the function and in MATLAB’s default work subdirectory C: MATLAB6p1work.

Once a function has been defined and saved in an M-file, it can be used from the Command Window. For example, to find the value of the function at 3π/2 we write in the Command Window:

>> fun1(3*pi/2)

ans =

95.2214

For help on the previous function (assuming that comments were added to the M-file that defines it) you use the command help, as follows:

>> help fun1(x)

A simple function definition

A function can also be evaluated at some given arguments (input parameters) via the feval command, the syntax of which is as follows:

feval ('F', arg1, arg1,..., argn)

This evaluates the function F (the M-file F.m) at the specified arguments arg1, arg2, . . . , argn.

As an example we build an M-file named equation2.m which contains the function equation2, whose arguments are the three coefficients of the quadratic equation ax2 + bx + c = 0 and whose outputs are the two solutions (Figure 6-13).

Now if we want to solve the equation x2 + 2 x + 3 = 0 using feval, we write the following in the Command Window:

>> [x 1, x 2] = feval('equation2',1,2,3)

x 1 =

-1.0000 + 1. 4142i

x 2 =

-1.0000 - 1. 4142i

The quadratic equation can also be solved as follows:

>> [x 1, x 2] = equation2 (1,2,3)

x 1 =

  -1.0000 + 1. 4142i

x 2 =

-1.0000 - 1. 4142i

If we ask for help about the function equation2 we do the following:

>>help equation2

This function solves the quadratic equation ax ^ 2 + bx + c = 0
whose coefficients are a, b and c (input parameters)
and whose solutions are x 1 and x 2 (output parameters)

Evaluating a function when its arguments (input parameters) are strings is performed via the command eval, whose syntax is as follows:

eval (expression)

This executes the expression when it is a string.

As an example, we evaluate a string that defines a magic square of order 4.

>>n=4;
>>eval(['M' num2str(n) ' = magic(n)'])

M4 =

16  2  3 13
5 11 10  8
9  7  6 12
4 14 15  1

Local and Global Variables

Typically, each function defined as an M-file contains local variables, i.e., variables that have effect only within the M-file, separate from other M-files and the base workspace. However, it is possible to define variables inside M-files which can take effect simultaneously in other M-files and in the base workspace. For this purpose, it is necessary to define global variables with the GLOBAL command whose syntax is as follows:

GLOBAL x y z...

This defines the variables x, y and z as global.

Any variables defined as global inside a function are available separately for the rest of the functions and in the base workspace command line. If a global variable does not exist, the first time it is used, it will be initialized as an empty array. If there is already a variable with the same name as a global variable being defined, MATLAB will send a warning message and change the value of that variable to match the global variable. It is convenient to declare a variable as global in every function that will need access to it, and also in the command line, in order to access it from the base workspace. The GLOBAL command is located at the beginning of a function (before any occurrence of the variable).

As an example, suppose that we want to study the effect of the interaction coefficients α and β in the Lotka–Volterra predator-prey model:

image

To do this, we create the function lotka in the M-file lotka.m as depicted in Figure 6-14.

Later, we might type the following in the command line:

>>global ALPHA BETA
ALPHA = 0.01
BETA = 0.02

These global values may then be used for α and β in the M-file lotka.m (without having to specify them). For example, we can generate the graph (Figure 6-15) with the following syntax:

>> [t, y] = ode23 ('lotka', 0.10, [1; 1]); plot(t,y)

Data Types

MATLAB has 14 different data types, summarized in Figure 6-16 below.

Below are the different types of data:

Data Type

Example

Description

single

3* 10 ^ 38

Simple numerical precision. This requires less storage than double precision, but it is less precise. This type of data should not be used in mathematical operations.

Double

3*10^300 5+6i

Double numerical precision. This is the most commonly used data type in MATLAB.

sparse

speye(5)

Sparse matrix with double precision.

int8, uint8, int16, uint16, int32, uint32

UInt8(magic (3))

Integers and unsigned integers with 8, 16, and 32 bits. These make it possible to use entire amounts with efficient memory management. This type of data should not be used in mathematical operations.

char

'Hello'

Characters (each character has a length of 16 bits).

cell

{17 'hello' eye (2)}

Cell (contains data of similar size).

structure

a.day = 12;
a.color = 'Red';
a.mat = magic(3);

Structure (contains cells of similar size).

user class

inline('sin (x)')

MATLAB class (built with functions)

java class

Java.awt.Frame

Java class (defined in API or own) with Java.

function handle

@humps

Manages functions in MATLAB. It can be last in a list of arguments and evaluated with feval.

Flow Control: FOR Loops, WHILE and IF ELSEIF

The use of recursive functions, conditional operations and piecewise defined functions is very common in mathematics. The handling of loops is necessary for the definition of these types of functions. Naturally, the definition of the functions will be made via M-files.

The FOR Loop

MATLAB has its own version of the DO statement (defined in the syntax of most programming languages). This statement allows you to run a command or group of commands repeatedly. For example:

» for i=1:3, x(i)=0, end

x =

0

x =

0     0

x =

0 0 0

The general form of a FOR loop is as follows:

for variable = expression
commands
end

The loop always starts with the clause for and ends with the clause end, and includes in its interior a whole set of commands that are separated by commas. If any command defines a variable, it must end with a semicolon in order to avoid repetition in the output. Typically, loops are used in the syntax of M-files. Here is an example (Figure 6-17):

In this loop we have defined a Hilbert matrix of order (m, n). If we save it as an M-file matrix1.m, we can build any Hilbert matrix later by running the M-file and specifying values for the variables m and n (the matrix dimensions) as shown below:

>> M = matrix1 (4,5)

M =

1.0000 0.5000 0.3333 0.2500 0.2000
0.5000 0.3333 0.2500 0.2000 0.1667
0.3333 0.2500 0.2000 0.1667 0.1429
0.2500 0.2000 0.1667 0.1429 0.1250

The WHILE Loop

MATLAB has its own version of the WHILE structure defined in the syntax of most programming languages. This statement allows you to repeat a command or group of commands a number of times while a specified logical condition is met. The general syntax of this loop is as follows:

while condition
commands
end

The loop always starts with the clause while, followed by a condition, and ends with the clause end, and includes in its interior a whole set of commands that are separated by commas which continually loop while the condition is met. If any command defines a variable, it must end with a semicolon in order to avoid repetition in the output. As an example, we write an M-file (Figure 6-18) that is saved as while1.m, which calculates the largest number whose factorial does not exceed 10100.

We now run the M-file.

>> while1

n =

70

IF ELSEIF ELSE END Loops

MATLAB, like most structured programming languages, also includes the IF-ELSEIF-ELSE-END structure. Using this structure, scripts can be run if certain conditions are met. The loop syntax is as follows:

if condition
commands
end

In this case the commands are executed if the condition is true. But the syntax of this loop may be more general.

if condition
commands1
else
commands2
end

In this case, the commands commands1 are executed if the condition is true, and the commands commands2 are executed if the condition is false.

IF statements and FOR statements can be nested. When multiple IF statements are nested using the ELSEIF statement, the general syntax is as follows:

if condition1
commands1
elseif condition2
commands2
elseif condition3
commands3
.
.
else
end

In this case, the commands commands1 are executed if condition1 is true, the commands commands2 are executed if condition1 is false and condition2 is true, the commands commands3 are executed if condition1 and condition2 are false and condition3 is true, and so on.

The previous nested syntax is equivalent to the following unnested syntax, but executes much faster:

if condition1
commands1
else
if condition2
commands2
else
if condition3
commands3
else
.
.
end
end
end

Consider, for example, the M-file else1.m (see Figure 6-19).

When you run the file it returns negative, odd or even according to whether the argument n is negative, non-negative and odd, or non-negative and even, respectively:

>>else1 (8), else1 (5), else1 (- 10)

A =

n is even

A =

n is odd

A =

n is negative

Switch and Case

The switch statement executes certain statements based on the value of a variable or expression. Its basic syntax is as follows:

switch expression (scalar or string)
casevalue1
statements % runs if expression is value1
casevalue2
statements % runs if expression is value2
.
.
.
otherwise
statements % runs if neither case is satisfied

end

Below is an example of a function that returns ‘minus one’, ‘zero’, ‘one’, or ‘another value’ according to whether the input is equal to −1,0,1 or something else, respectively (Figure 6-20).

Running the above example we get:

>> case1 (25)
another value

>> case1 (- 1)
minus one

Continue

The continue statement passes control to the next iteration in a for loop or while loop in which it appears, ignoring the remaining instructions in the body of the loop. Below is an M-file continue.m (Figure 6-21) that counts the lines of code in the file magic.m, ignoring the white lines and comments.

Running the M-file, we get:

>> continue1
25 lines

Break

The break statement terminates the execution of a for loop or while loop, skipping to the first instruction which appears outside of the loop. Below is an M-file break1.m (Figure 6-22) which reads the lines of code in the file fft.m, exiting the loop as soon as it encounters the first empty line.

Running the M-file we get:

>> break1

%FFT Discrete Fourier transform.
%   FFT(X) is the discrete Fourier transform (DFT) of vector X.  For
%   matrices, the FFT operation is applied to each column. For N-D
%   arrays, the FFT operation operates on the first non-singleton
%   dimension.
%
%   FFT(X,N) is the N-point FFT, padded with zeros if X has less
%   than N points and truncated if it has more.
%
%   FFT(X,[],DIM) or FFT(X,N,DIM) applies the FFT operation across the
%   dimension DIM.
%
%   For length N input vector x, the DFT is a length N vector X,
%   with elements
%                    N
%      X(k) =       sum  x(n)*exp(-j*2*pi*(k-1)*(n-1)/N), 1 <= k <= N.
%                   n=1
%   The inverse DFT (computed by IFFT) is given by
%                    N
%      x(n) = (1/N) sum  X(k)*exp( j*2*pi*(k-1)*(n-1)/N), 1 <= n <= N.
%                   k=1
%
%   See also IFFT, FFT2, IFFT2, FFTSHIFT.

Try ...  Catch

The instructions between try and catch are executed until an error occurs. The instruction lasterr is used to show the cause of the error. The general syntax of the command is as follows:

try,
instruction
...,
instruction
catch,
instruction
...,
instruction
end

Return

The return statement terminates the current script and returns the control to the invoked function or the keyboard. The following is an example (Figure 6-23) that computes the determinant of a non-empty matrix. If the array is empty it returns the value 1.

Running the function for a non-empty array we get:

>> A = [-1,-1,1; 1,0,1; 1,1,1]

A =
-1 -1 -1
1  0  1
1 -1 -1

>> det1 (A)

ans =

2

Now we apply the function to an empty array:

>> B =[]

B =

     []

>> det1 (B)

ans =

     1

Subfunctions

M-file-defined functions can contain code for more than one function. The main function in an M-file is called a primary function, which is precisely the function which invokes the M-file, but subfunctions hanging from the primary function may be added which are only visible for the primary function or another subfunction within the same M-file. Each subfunction begins with its own function definition. An example is shown in Figure 6-24.

The subfunctions mean and median calculate the arithmetic mean and the median of the input list. The primary function newstats determines the length n of the list and calls the subfunctions with the list as the first argument and n as the second argument. When executing the main function, it is enough to provide as input a list of values for which the arithmetic mean and median will be calculated. The subfunctions are executed automatically, as shown below.

>> [mean, median] = newstats ([10,20,3,4,5,6])

mean =

     8

median =

    5.5000

Ordinary Differential Equations Using Numerical Analysis

Obtaining exact solutions of ordinary differential equations is not a simple task. There are a number of different methods for obtaining approximate solutions of ordinary differential equations. These numerical methods include, among others, Euler’s method, Heun’s method, the Taylor series method, the Runge–Kutta method (implemented in MATLAB’s Basic module), the Adams–Bashforth–Moulton method, Milne’s method and Hamming’s method.

Euler’s Method

Suppose we want to solve the differential equation y ' = f (t, y),  y(a) =y0, on the interval [a, b]. We divide the interval [a, b] into M subintervals of the same size using the partition given by the points tk = a +kh, k = 0,1,..., M, h = (b-a)/M. Euler’s method then finds the solution of the differential equation iteratively by calculating yk+1 = yk + hf (tk, yk),  k = 0,1, ..., M−1.

Euler’s method is implemented using the M-file shown in Figure 6-25.

Heun’s Method

Suppose we want to solve the differential equation y ' = f(t, y), y(a) =y0, on the interval [a, b]. We divide the interval [a, b] into M subintervals of the same size using the partition given by the points tk = a + kh, k = 0,1,..., M, h= (b-a)/M. Heun’s method then finds the solution of the differential equation iteratively by calculating yk + 1 = yk+ h(f (tk, yk) + f (tk + 1, yk+ f (tk, yk)))/2, k = 0,1,..., M−1.

Heun’s method is implemented using the M-file shown in Figure 6-26.

The Taylor Series Method

Suppose we want to solve the differential equation y' = f (t, y), y(a) = y0, on the interval [a, b]. We divide the interval [a, b] into M subintervals of the same size using the partition given by the points tk = a + kh, k = 0,1,..., M, h = (b-a)/M. The Taylor series method (let us consider here the method to order 4) finds a solution to the differential equation by evaluating y', y", y"' and y"" to give the 4th order Taylor series for y at each partition point.

The Taylor series method is implemented using the M-file shown in Figure 6-27.

As an example we solve the differential equation y'(t) = (t - y)/2 on the interval [0,3], with y(0) = 1, using Euler’s method, Heun’s method and by the Taylor series method.

We will begin by defining the function f (t, y) via the M-file shown in Figure 6-28.

The solution of the equation using Euler’s method in 100 steps is calculated as follows:

>>E = euler('dif1',0,3,1,100)

E =

0 1.00000000000000
0.03000000000000 0.98500000000000
0.06000000000000 0.97067500000000
0.09000000000000 0.95701487500000
0.12000000000000 0.94400965187500
0.15000000000000 0.93164950709688
0.18000000000000 0.91992476449042
.
.
.
2.85000000000000 1.56377799005910
2.88000000000000 1.58307132020821
2.91000000000000 1.60252525040509
2.94000000000000 1.62213737164901
2.97000000000000 1.64190531107428
3.00000000000000 1.66182673140816

This solution can be graphed as follows (see Figure 6-29):

>>plot (E (:,2))

The solution of the equation by Heun’s method in 100 steps is calculated as follows:

>> H = heun('dif1',0,3,1,100)
H =
0 1.00000000000000
0.03000000000000 0.98533750000000
0.06000000000000 0.97133991296875
0.09000000000000 0.95799734001443
0.12000000000000 0.94530002961496
.
.
.
2.88000000000000 1.59082209379464
2.91000000000000 1.61023972987327
2.94000000000000 1.62981491089478
2.97000000000000 1.64954529140884
3.00000000000000 1.66942856088299

The solution using the Taylor series method requires the previously defined function df = [y' y'' y''' y''''] using the M-file shown in Figure 6-30.

The differential equation is solved by the Taylor series method via the command:

>> T = taylor('df',0,3,1,100)

T =
0 1.00000000000000
0.03000000000000 0.98533581882813
0.06000000000000 0.97133660068283
0.09000000000000 0.95799244555443
0.12000000000000 0.94529360082516
.
.
.
2.88000000000000 1.59078327648360
2.91000000000000 1.61020109213866
2.94000000000000 1.62977645599332
2.97000000000000 1.64950702246046
3.00000000000000 1.66939048087422

EXERCISE 6-1

Find an approximate solution of the following differential equation in the interval [0, 0.8]:

image

We start by defining the function f(t,y) via the M-file shown in Figure 6-31.

We then solve the differential equation by Euler’s method in 20 steps by using the following syntax:

>> E = euler('dif2',0,0.8,1,20)

E =
0 1.00000000000000
0.04000000000000 1.04000000000000
0.08000000000000 1.08332800000000
0.12000000000000 1.13052798222336
0.16000000000000 1.18222772296696
0.20000000000000 1.23915821852503
0.24000000000000 1.30217874214655
0.28000000000000 1.37230952120649
0.32000000000000 1.45077485808625
0.36000000000000 1.53906076564045
0.40000000000000 1.63899308725380
0.44000000000000 1.75284502085643
0.48000000000000 1.88348764754208
0.52000000000000 2.03460467627982
0.56000000000000 2.21100532382941
0.60000000000000 2.41909110550949
0.64000000000000 2.66757117657970
0.68000000000000 2.96859261586445
0.72000000000000 3.33959030062305
0.76000000000000 3.80644083566367
0.80000000000000 4.40910450907999

The solution can be graphed (Figure 6-32) as follows:

>> plot(E(:,2))
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset