Académique Documents
Professionnel Documents
Culture Documents
5/13/12
Differential Equation Solvers Function Handles and Anonymous Functions First Order Differential Equation Second Order Differential Equations Initial Value Problems Boundary Value Problems
5/13/12
MATLAB includes a number of functions that solve ordinary differential equations of the form
Higher order differential equations and systems of differential equations must be reformulated into a system of first order expressions.
5/13/12
Not every differential equation can be solved using the same technique. All of the differential equation solvers in MATLAB have the same format. This makes it easy to try different techniques, by just changing the function name. MATLAB includes a large family of differential equation solvers. A good first try is usually the ode23 or ode45 solver function, which uses a RungeKutta technique.
5/13/12
- the time span of interest - an initial condition for each equation in If you do not specify the result array, [t,y] , the system. the functions create a plot of the results
[t,y] = odesolver(function_handle, [initial_time, final_time], [initial_cond_array])
5/13/12
Type of problems likely to be solved with this technique non-stiff differential equations
Numerical Comments Solution Method Runge-Kutta Best choice for a first guess technique, if you dont know much about the function. Uses an explicit Runge-Kutta (4,5) formula, called the Dormand-Prince pair
ode23
Runge-Kutta
This techniques uses an explicit Runge-Kutta (2,3) pair of Bogacki and Shampine. If the function is mildly stiff this may be a better approach Unlike ode45 and ode23 which are single step solvers, this technique is a multistep solver. Uses numerical differentiation formulas or backward differentiation formulas. It is difficult to predict which technique will work best for a stiff differential equation modified second order Rosenbock formulation Useful if you need a solution without numerical damping
ode113 ode15s
Adams
stiff differential equation and differential NDFs (BDFs) algebraic equations stiff differential equations Rosenbrock
ode23s ode23t
moderately stiff differential equations and Trapazoid rule differential algebraic equations stiff differential equations TR-BDF2
ode23tb
This solver uses an implicit Runge-Kutta formula with the trapazoid rule and a second order backward differentiation formula.
ode15i
5/13/12
Function Handles
A function handle is a nickname (alias name) for a function. The function handle can refer to
an anonymous MATLAB function. Anonymous functions can be defined in an M-file program, or in the command window.
5/13/12
5/13/12
You can use an anonymous function as input to an ode solver function Because we did not assign a name to the ode function output, a graph is created. See next slide.
5/13/12
This figure was generated automatically by the ode45 function. The title and labels were added in the usual way.
5/13/12
If you want to specify a system of equations, it is probably easier to use a function M-file. The output of the function must be a column vector of first derivative values. For example:
5/13/12
5/13/12
We can now use an M-file function as input to an ODE solver The handle for an existing M-file is @m_file_name ode45(@another_fun, [-1,1],
[1,1])
5/13/12
-0.5
0 time
0.5
This system of equations was solved using ode45. The 5/13/12 title, labels and legend were added in the
The initial value problem of the 1st order differential equation is of the form y'(t) = f(t), y(0) = a It can be solved in MATLAB using functions ode23 or ode45. Example: RL- circuit (a resistor and an inductor) L I + R I = E,
5/13/12
where
RL Circuit
di = E/L - (R/L)*i;
5/13/12
title('RL Circuit')
A typical example of a system that undergoes simple harmonic motion is an idealized spring mass system, in which is a mass is attached to a spring. The differential equation is m x + b x + k x = mg, where k=10, b=2, g=9.81, m=2 x1 = x We x2 = x1 have to solve the system of two equations: x1 = x2 x2 = - (k/m) x1 (b/m) x2 + g
5/13/12
Solution in MATLAB
x = x_2
Instead of the matrix form the system of differential equations can be written in the function string.m alternatively also in the component form:
function xe=string(t,x) k=10; b=2; g=9.81; m=2; xe(1) = x(2); xe(2) = (-k/m)*x(1) + (-b/m)*x(2) + g;
5/13/12
To pin down the constant C1 we need a boundary condition. To find C1, we need a boundary condition that tells us some value of y(t): e.g. y(1)=2.
Symbolic Toolbox is an optional toolbox that allows symbolic computations. 5/13/12 It must be installed separately on your computer.
5/13/12
Interpolate between data points, using either linear or cubic spline models. Perform numerical differentiations Perform numerical integrations Solve differential equations numerically Root Finding and Minimization
5/13/12
Interpolation: Summary
MATLAB includes an interpolation technique called interp1. Its is the most commonly used function for linear interpolations. A cubic spline technique is also available.
5/13/12
Linear Interpolation
Assume the function between two points is a straight line.
12
A Data Plot
Measured Data
16 14
10
Interpolated Point
y-axis
12 10 8 6 4
Interpolated Points
y-axis
2 0
-1
x-axis
x-axis
interpolation.
First define an array of x and the y values. Now define a new x array, that includes the x values for which you want to find y values
new_y=interp1(x,y, x_new)
5/13/12
Interpolation is the technique of creating new data points within existing points MATLAB has built-in interpolation functions for both 1-D and 2-D interpolation. 1-D Syntax
ynew = interp1(xorig,yorig,xnew,method) Where ynew - new y value(s) xorig, - original x values
'nearest - nearest neighbor interpolation 'linear (default) 'spline (cubic spline interpolation 'cubic (piecewise cubic)
Measured Data
16 14 12 10
y-axis
8 6 4 2 0 -1 0 1 2 3 4 5 6
x-axis
5/13/12
Cubic Spline - A cubic spline creates a smooth curve, using a third degree polynomial MATLAB includes other interpolation techniques including
5/13/12
5/13/12
16 14 12 10
y-axis
8 6 4 2 0 -1 0 1 2 3 4 5 6
x-axis
Cubic Spline Interpolation. The data points on the smooth curve were calculated. The data points on the straight line segments were measured. Note that every measured point 5/13/12 also falls on the curved line.
Interpolation: Demo
Perform the following: >> x = 0:12;
Create a vector from 0 to 12 Evaluate cosine at every x value. Create a more fine spacing Create new y values at the finer x spacing. Repeat the interpolation but with a cubic spline technique. Plot the three datasets the original, the default interpolation and the cubic spline interpolation
>> y = cos(x);
>> xi = linspace(0,12,50);
>> yi = interp1(x,y,xi);
1 . 5
0 . 5
1 0
1 0
% Now assume have only the points, but not the function xx = 0:.1:4pi sampling yy = interp1(x,y,xx); hold on 5/13/12 % finer
Numerical Derivatives
The diff function finds the difference between adjacent elements in an array It can be used to approximate a derivative.
5/13/12
Function diff
Numerical differentiation uses the diff function. The diff function is easy to understand, even if you have not taken calculus. It just calculates the difference between the points in an array. If we know how y changes with x, we could create a set of ordered pairs for any number of x values. The more values of x and y, the better the 5/13/12 approximation of the slope.
2 xa is -x
The derivative of a data set can be approximated by finding the slope of a straight line connecting 5/13/12 data point each
Numerical Derivative
Finite differences can be used to compute a numerical derivative. MATLAB provides a built-in function for calculating numerical derivative using the forward difference method.
It is easy to create your own difference formula by taking advantage of MATLABs vector processing. 5/13/12
If you have a function that you want to differentiate, first evaluate the function using a small Dx, then put the resulting data through diff
The slope is an approximation of the derivative in this case based on data measurements
5/13/12
Perform the following: >> xi = 0:0.25:12; >> yi= xi.*2 + xi; >> yi_diff1 = diff(yi,1); >> yi_diff2 = diff(yi,2); >> xi_diff1 = diff(xi,1); >> xi_diff2 = diff(xi,2); >> plot(yi,b-);
20
Create a vector from 0 to 12 Evaluate your function Calculate the first y difference Calculate the second y difference Repeat for the xs
Plot your three different lines, making sure to divide by the xs.
15
10
15
20
25
30
35
40
45
50
Numerical Integration
quad uses adaptive Simpson quadrature quadl uses adaptive Lobatto quadrature
Both functions require the user to enter a function in the first field.
The last two fields in the function define the limits of integration
5/13/12
5/13/12
10 y-axis y-axis 5
10
2 x-axis
2 x-axis
The area under a curve can be approximated using the trapezoid rule.
5/13/12
Numerical Integration
You integrate to either determine the area under the curve, or as part of a differential equation. There are times when you cannot integrate a function analytically. The trapezoidal method is a common technique for computing area under the curve. If noise in your data is a problem, fit the data to a function or smooth your data with averaging.
MATLAB provides several built-in functions for computing area under the curve trapz function calculates area for data sets quad function calculates area for functions Syntax
area = trapz(x,y) Where x vector of x data y - vector of y data area = quad(fn,lo,hi) Where fn the function to evaluate lo lower bound hi upper bound
5/13/12
Normally you would use the trapz function if you did not have a function and only data
quad function:
>> area = quad('x.^3 ./ (exp(x) - 1)',001,15) area = 6.4927 5/13/12
Rounded answer: 6.4939
Data Problems
Do not really want to exactly fit to the points Real question: what is the "best fit" n is "degree" of the polynomial returns coefficients polyval(coeffs,X) evals at vector X using those coeffs go through sparse data (knot points);
Splines 5/13/12
Interpolation vs Extrapolation
Interpolation is MUCH better behaved has at least two points to help. Extrapolation is often really ugly
5/13/12
Noise in the data will impact the calculation and requires work-arounds. Fit the data to a function, then differentiate the function analytically or with numerical methods. Filter (smooth) the data, then differentiate the smoothed data. Filtering can change calculated derivative values. Watch out for a shift in your data when using moving averages. Use the Less is More approach.
0 -2 -4 Pressure -6 100 -8 dP/dT -10 -12 -14 0 10 20 Time -100 -150 0 10 20 Time 30 40 50 0 -50 30 40 150
Original Data
5/13/12
These functions use a mathematical technique called convolution. In convolution, you have a data set, and what is termed a kernel. The weighting of the average depends on the values used in the kernel. The kernel is slid along the data set, elements are multiplied together, the results are summed and a new data set is built from the results.
Kernel values should sum to 1 or else you will change the mean level of your data! Unequal kernel values will give a weighted average 5/13/12
ysmooth = filter( kernel, 1, yorig) Where: convn with the same option does not cause a data shift, whereas filter will row or column by the number of points yorig shift the data data to smooth used in the smoothing. column vector of filter weights kernel row or
5/13/12
Create a [5x1] vector where each value = 0.2 and the sum =1 Moving avg with convn Moving avg with filter Plot data and build a legend
0 .5
- .5 0
5/13/12
1 0
MATLAB provides built-in functionality finding the zeros and minima of a function. Syntax
ymin = fminsearch(fcn,xguess) yzero = fzero(fcn,xguess) Where fcn function to search xguess guess at the minimum
fminsearch function:
>> z1 = fzero('sin(x)', x0) >> z1 = fzero('sin(x)', x0, tol) >> z1 = fzero('sin(x)', x0, tol, trace)
5/13/12
First write the definition for the system of the equations in the file eqns.m
function eq=eqns(p); %EQNS defines the left hand side of equations
% The system of the nonlinear equations to be solved is % x^2 + y^2 - 3xy = 0 % x^2 + y = 0 x = p(1); y = p(2); eq = zeros(2,1); eq(1) = x^3 + y^3 - 3*x*y; eq(2) = x^2 + y;
5/13/12
Symbolic Derivatives
Symbolic Toolbox is an optional toolbox that allows symbolic computations in MATLAB. It must be installed separately on your computer. 5/13/12
5/13/12
Symbolic Integration
5/13/12
5/13/12
5/13/12
5/13/12
5/13/12