0% found this document useful (0 votes)
8 views

Chapter 13 - Differential Equation (1) Student

The document discusses differential equations and related topics in scientific programming. It covers function handles, anonymous functions, integration and differentiation functions in MATLAB. Examples are provided to demonstrate how to create anonymous functions from math expressions and existing functions, as well as how to use function handles with functions like integral() and diff().

Uploaded by

qjm9n9hx7x
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Chapter 13 - Differential Equation (1) Student

The document discusses differential equations and related topics in scientific programming. It covers function handles, anonymous functions, integration and differentiation functions in MATLAB. Examples are provided to demonstrate how to create anonymous functions from math expressions and existing functions, as well as how to use function handles with functions like integral() and diff().

Uploaded by

qjm9n9hx7x
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

PROGRAMMING

SCIENTIFIC
SKEE1022
DIFFERENTIAL
EQUATION
( WEEK 14 )

DR. USMAN ULLAH SHEIKH


DR. MUSA MOHD MOKJI
DR. MICHAEL TAN LOONG PENG
DR. AMIRJAN NAWABJAN
DR. MOHD ADIB SARIJARI
OBJECTIVES
After studying this chapter you should be able to:
• Understand and create function handle to available function.
• Understand and create anonymous function from mathematical
expression and existing function.
• Understand and use the function functions.
• Solve integration and difference using integral() and diff()
functions.
• Solve differential equation using ode23() function.
FUNCTION HANDLE
WHAT IS FUNCTION HANDLE

 A function handle is a MATLAB variable that stores an association (a


handle) to a function. With the handle, a function can be called
indirectly.
 The data type of this variable is written as function_handle.
 To create a handle for a function, precede the function name with an
@ sign. For example, below is how y is set as the function handle to
function myfunction():
y = @myfunction;

 Usage of the function handle:


1) To construct anonymous function.
2) To pass a function to another function (known as function functions).
3) To call local functions from outside the main function.

UNIVERSITI TEKNOLOGI MALAYSIA 4


ANONYMOUS FUNCTION

 Recap: Generally, function is a program that can accept inputs and


return outputs.
 Similar to the standard function, anonymous function can also accept
inputs and return outputs.
 The differences are:
1) Instead of a program file, anonymous function is a variable. The data
type of anonymous function is function_handle. The @ operator creates
the handle.
2) Anonymous function can contain only a single executable statement.
3) Since anonymous function is a variable, saving the function is similar to
saving other type of variable. E.g., using the save() function.
4) It is called anonymous function because the function does not have a
name while standard function comes with a name. Anonymous function
is called indirectly upon its function handle name.

UNIVERSITI TEKNOLOGI MALAYSIA 5


CREATING ANONYMOUS FUNCTION

 Syntax:
Handle creator
f = @(x) executable statement
Function Input
handle name argument

 The executable statement can be either one of the followings:


1) Mathematical expression.
2) Named function.

 The output arguments are not define explicitly. The number of the output
arguments is depending on the executable statement type.
1) Mathematical expression: Single output argument.
2) Named Function: Similar to the output arguments of the named function.

UNIVERSITI TEKNOLOGI MALAYSIA 6


ANONYMOUS FUNCTION TO MATH EXPRESSION

 Example 13.1
Below is a standard function save as .m file. Since the function only consist of a
single executable statement, the function can also be written as anonymous
function.
function f = mypoly(x)
f = x^2 + 1;

Below is how the function is written as anonymous function.


>> mypolyFH = @(x) x^2 + 1
mypolyFH =

function_handle with value:


@(x)x^2+1

>> a = mypolyFH(2)
a =
5

UNIVERSITI TEKNOLOGI MALAYSIA 7


ANONYMOUS FUNCTION TO NAMED FUNCTION

 Example 13.2
Writing available function as an anonymous function is a way to simplify the
function. For example, meshgrid is a function that accept vectors as input and
can return up to 3 output arguments. At certain situation, this function can be
simplified as anonymous function to accept scalars rather than vectors.
>> mygrid = @(x)meshgrid(0:x,0:2);

>> [a,b] = mygrid(4)


a =
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4

b =
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2

UNIVERSITI TEKNOLOGI MALAYSIA 8


ADDITIONAL PARAMETERS

 Additional parameters to the anonymous function are variables define


in the executable statement but not declared as input to the function.
For example, below is an anonymous function with one additional
parameter z.
y = @(x) x.^2 + z

 The value of z must be define before the anonymous function is created.


 This additional parameters will be useful to add extra variables to the
function input of the function functions.
 Next slide will discuss on the function functions.

UNIVERSITI TEKNOLOGI MALAYSIA 9


FUNCTION FUNCTIONS

 A function that accept function handle as its input argument is called function
functions.
 Since anonymous function is also a function handle, it can be used as the input
to the function functions.
 Later in this chapter, function integral() and ode45() are both the
example of function functions.
 Creating function input for function functions should follow the input argument
requirement of the function functions.
 For example, function integral() specify the function input as below:

UNIVERSITI TEKNOLOGI MALAYSIA 10


FUNCTION FUNCTIONS

 Example 13.3
 To plot 2 3 for 0: 0.1: 10, below is the MATLAB code when
using function plot():
>> x = 0:0.1:10;
>> y = 2*x.^2 + 3;
>> plot(x,y)

 We can simplify the code as below using function fplot() where an


anonymous function is used as the function handle to the fplot():
>> fplot(@(x)2*x.^2+3,[0 10])

UNIVERSITI TEKNOLOGI MALAYSIA 11


FUNCTION FUNCTIONS

 Alternatively, we can write a function file for the equation and use function
handle to call the function as below.
function y = myEq(x)
y = 2*x.^2+3;

>> fplot(@myEq,[0 10])

UNIVERSITI TEKNOLOGI MALAYSIA 12


ADDITIONAL PARAMETER EXAMPLE

 Example 13.4
Below is MATLAB script showing c as the additional parameter to the
anonymous function.
for c = 10:5:25
subplot(2,2,c/5-1), fplot(@(x)2*x.^3-c*x.^2+2,[0 10])
xlabel('x')
ylabel('y = 2x^3 - cx^2 + 2')
title(['Plot for c = ' num2str(c)])
end

UNIVERSITI TEKNOLOGI MALAYSIA 13


ADDITIONAL PARAMETER EXAMPLE

UNIVERSITI TEKNOLOGI MALAYSIA 14


INTEGRATION & DIFFERENTIATION
INTEGRATION FUNCTION: INTEGRAL

• Syntax
y = integral(fun,xmin,xmax)

Description
fun : Integrand, specified as a function handle, which defines the
function to be integrated from xmin to xmax.
For scalar‐valued problems, the function y = fun(x) must accept a
vector argument, x, and return a vector result, y. This generally
means that fun must use array operators instead of matrix
operators. For example, use .* (times) rather than * (mtimes). If
you set the 'ArrayValued' option to true, then fun must accept a
scalar and return an array of fixed size.
xmin : Lower limit of x.
xmax : Upper limit of x.
y : Integration result.
INTEGRAL

 Example 13.5
Solve:
.
1 2 6 1 2 1
.

>> y1 = integral(@(x)2*x.^2+6*x+1,0,10)

y1 =

976.6667

>> y2 = integral(@(x)x.^2+1,5.5,16.1)

y2 =

1.3462e+03

UNIVERSITI TEKNOLOGI MALAYSIA 17


THINKING TIME!!

 Example 13.6 ‐ Area under graph


Given 2 functions of shown on the above figure, find the area of the shaded
region.

Solution
1) Find by finding roots of when . Or, it is the roots of .
2) Find area under both the quadratic function, and linear function, for
from 0 to .
3) If area under graph is and area under graph is , area of the
shaded area is then
UNIVERSITI TEKNOLOGI MALAYSIA 18
DERIVATIVE FUNCTION: diff()/h

 Syntax
Y = diff(X,n)/h^n %Approximate Derivatives

Description
X : Input array.
n : Derivative order.
h : Interval between data points.
Y : Difference result.

UNIVERSITI TEKNOLOGI MALAYSIA 19


DERIVATIVE

 Example 13.7
Find derivative of 9.8 20.13 0.03 for 0 10.
h = 0.001;
t = 0:h:10;
y = 9.8*t.^2 + 20.13*t - 0.03;
dydt = diff(y)/h;

plot(t(2:end),[y(2:end); dydt])
xlabel('t')
title('Derivative Approximation Using diff()/h')
legend('y(t)','y''(t)’)

>> size(y)
ans =
1 10001
Note that the size of
>> size(dydt)
dydt is always shorter by
ans =
1 10000
1 sample compared to y.

UNIVERSITI TEKNOLOGI MALAYSIA 20


DERIVATIVE

UNIVERSITI TEKNOLOGI MALAYSIA 21


DERIVATIVE APPROXIMATION ERROR

 Example 13.8
• Differentiate the following function for 0 1 using the diff()/h
function.

0.3 20 180 650 880 360

• Then, compare the results with the exact solution given by:

20 360 1950 3520 1800

• To do the above, write a script that estimates the differentiation of by


setting equals to 1, 0.5 and 0.1, and compares the results with the exact
solution graphically.
DERIVATIVE APPROXIMATION ERROR

 Below is the MATLAB script for Example 13.8


h = [1 0.5 0.1 0.01];
linestyle = {':k','--b','-.r','-'};
for n = 1:4
x = 0:h(n):10;
y = 0.3 + 20*x - 180*x.^2 + 650*x.^3 - 880*x.^4 + 360*x.^5;
ydot = diff(y)/h(n);
plot(x(2:end),ydot,linestyle{n})
hold on
end

x = 0:0.001:10;
ydotexact = 20 - 360*x + 1950*x.^2 - 3520*x.^3 + 1800*x.^4;

plot(x(2:end),ydotexact(2:end),'k','LineWidth',1)
xlabel('x')
ylabel('y''(x)')
title('Derivative Approximation Error')
legend('h=1','h=0.5','h=0.1','Exact solution')
hold off

UNIVERSITI TEKNOLOGI MALAYSIA 23


DERIVATIVE APPROXIMATION ERROR

* The error decreases when h value becomes smaller.


In this example, 0.01 gives unnoticeable error.

UNIVERSITI TEKNOLOGI MALAYSIA 24


2ND ORDER DERIVATIVE

 Example 13.9

• Solve and plot for the following function. Set time span from 0 to 50 .
4.0622 05 0.0036 0.0229 1.4151
• Then find 5 .

h=0.01;
t = 0:h:50;
y = -4.0622e-05*t.^4 + 0.0036*t.^3 - 0.0229*t.^2 + 1.4151*t;
ydot = diff(y,2)/h^2;

plot(t(3:end),ydot)
xlabel('x') 2nd order results is
ylabel('y''''(x)')
always shorter by 2
title('2^{nd} Order Derivative')
samples compared to
fprintf('y''''(5) = %.4f\n',ydot(5/h+1)) the original vector y.

y''(5) = 0.0502

UNIVERSITI TEKNOLOGI MALAYSIA 25


2ND ORDER DERIVATIVE

UNIVERSITI TEKNOLOGI MALAYSIA 26


DIFFERENTIAL EQUATION
DIFFERENTIAL EQUATION

 Differential equation is an equation involving derivatives of a function.


 In MATLAB, differential can be solve using function ode23().
 Syntax
[t,y] = ode23(odefun,tspan,y0)

Description
odefun : Function to be solve, specified as function handle.
tspan : Integral interval.
y0 : Initial condition.
y : Solution.
t : Evaluation points

UNIVERSITI TEKNOLOGI MALAYSIA 28


odefun FUNCTION HANDLE

 Above is the description from the MATLAB documentation of the function handle
for function ode23().
 The example given in the documentation can also be written as an anonymous
function as below:
@(t,y)5*y-3

UNIVERSITI TEKNOLOGI MALAYSIA 29


CHARGING OF AN RC CIRCUIT

 Example 13.10
To find how the capacitor is charging, below is the differential equation of above
circuit derived from KCL

By setting 10 Ω, 10 , 10 and 0 at 0, use function


ode23() to plot the for from 0 to 2 .

UNIVERSITI TEKNOLOGI MALAYSIA 30


CHARGING OF RC CIRCUIT

Solution
To solve the differential equation for using function ode23():
1) Rearrange the equation by setting the placed at the left side of the
equation as below and write the appropriate odefun function handle.
10
100 10
0.1
odefun = @(t,vc)100-10*vc
2) Set initial value for . In this example, it is set to 0.
3) Set time interval. In this example, it is set as [0 2].
4) Write the ode23() function and run the code.

UNIVERSITI TEKNOLOGI MALAYSIA 31


CHARGING OF RC CIRCUIT

 Below is the MATLAB script for Example 13.10


[t,vc] = ode23(@(t,vc)100-10*vc, [0 2], 0);

plot(t,vc)
xlabel('t(s)'), ylabel('v_c (t)')
title('Charging of RC Circuit')
grid on

UNIVERSITI TEKNOLOGI MALAYSIA 32


CHARGING OF RC CIRCUIT

v (t)
c

 It can be seen from the above figure, the steady state voltage of the capacitor is
10 , which is similar to the .

UNIVERSITI TEKNOLOGI MALAYSIA 33


CHARGING AND DISCHARGING OF RC CIRCUIT

 Example 13.11
Repeat example 13.10 with the following .

1 1
0

0
0 1 2

Solution
Above can be coded as 1*(t<1) or simply as (t<1). The only modification
needed for function odefun() is to replace the with the new equation
where the derivative equation is now ddt=((t<1)-vc)/0.1.

UNIVERSITI TEKNOLOGI MALAYSIA 34


CHARGING OF RC CIRCUIT

Solution
To solve the differential equation for using function ode23():
1) From Example 13.10, we have
10
In this example, is no longer a constant value where its value turns to 0
when 1. To solve this, we can code either using decision statement
or logical vector. Since anonymous function can only have one executable
statement, logical vector method is used in this example. Here can be
coded as 1*(t<1) or simply as (t<1) and the odefun function handle is
written as below:
odefun = @(t,vc)10*((t<1)-vc)

2) Similar to Example 13.10, initial value for is 0 and time interval is[0 2].
3) Write the ode23() function and run the code.

UNIVERSITI TEKNOLOGI MALAYSIA 35


CHARGING AND DISCHARGING OF RC CIRCUIT

 Below is the MATLAB script for Example 13.11


[t,vc] = ode23(@(t,vc)10*((t<1)-vc), [0 2], 0);

plot(t,vc)
xlabel('t(s)')
ylabel('v_c (t)')
title('Charging and Discharging of RC Circuit')
grid on

UNIVERSITI TEKNOLOGI MALAYSIA 36


CHARGING AND DISCHARGING OF RC CIRCUIT
vc (t)

UNIVERSITI TEKNOLOGI MALAYSIA 37


2ND ORDER DIFFERENTIAL EQUATION

 Function ode23() only solve 1st order differential equation. Thus, to


solve the 2nd order differential equation, two stage 1st order
differentiation is written in for the odefun function handle.
 For example, to solve 2 5 1, write the function as the
following by setting and :

2 5 1

odefun = @(t,y)[y(2); 2*y(2)+5*y(1)+1];

1st derivative. 2nd derivative. Written


Always written according to the differential
it this way. equation to be solved.

UNIVERSITI TEKNOLOGI MALAYSIA 38


2ND ORDER DIFFERENTIAL EQUATION

 Then, the function ode23() is given with 2 initial values (one for and
one for ), specified as a vector. In this example the initial value is
specified by vector
inity = [ ]=[0 0]

tspan = [0 2];
inity = [0 0];
[t,y] = ode23(@odefun(t,y),inity,tspan);

function d2dt = odefun(t,y)


d2dt = [y(2); 2*y(2)+5*y(1)+1];

UNIVERSITI TEKNOLOGI MALAYSIA 39


THINKING TIME!!

1Ω 10

10

 Example 13.12 ‐ RLC resonance circuit


 One of the RLC circuit usage is as a resonance circuit, a circuit that generate
an oscillating signal at specific frequency. The frequency can be computed as:
1
2

 The differential equation of the above RLC circuit is as below where the
inductor contributed to the 2nd order differential equation. Plot for
equals to 50 , 100 and 635 .

UNIVERSITI TEKNOLOGI MALAYSIA 40


RLC RESONANCE CIRCUIT

Solution
To solve the differential equation for using function ode23():
1) Rearrange the equation by setting the placed at the left side of the
equation as below and write it in the function odefun().
10 /10

2) Write the differential equation as 1st derivative equation by setting


and .

10 /10

3) Set initial value for and as [0 0]and time interval as[0 2].
4) Write the ode23() function and run the code.
5) is set as the additional parameter to the anonymous function since
function ode23() allowed only two inputs to the anonymous function.

UNIVERSITI TEKNOLOGI MALAYSIA 41


EXAMPLES OF OTHER SYSTEM

System

1) Parallel RLC Circuit:

Differential 1 1
0
Equation

Odefun @(t,V)[V(2); -V(2)/(R*C)-V(1)/(L*C)]

2) 2nd Order Active Lowpass Filter:

Differential 1.4142Ω Ω
Equation Where Ω is the filter cutoff frequency in and is the filter gain

Odefun @(t,vout)[vout(2); H*vin-1.4142*wc*vout(2)-(wc^2)*vout(1)];

UNIVERSITI TEKNOLOGI MALAYSIA 42

You might also like