Hello, is it possible to use a non -explicit function in de file ode23

A piecewise defined function needs a description per interval and hence has no explicit fromule like f(x)=x^2, since it changes per interval. My question if it is possible to define a piecewise function say: f(x)=1 on x in [0,10] and f(x)=3x+4 on [10,20] and then use ode23 to solve the first order differential equation. At the moment I split the solving in the separate intervals, but I'm not sure if it effects the solution. My specific example is using the function:
function f=fun1(x,h)
f=(-(10*h)/(10*x-100)-0.001)/((((10*x-100)^2)*9.81*h^3/(1200^2))-1);
end
and then solving h(x):
[tv1 f1]=ode23('fun1',[0 10],1);
And then the next interval I replace 10x-100 by 3x+4 in the function fun1 and use another interval in solving it.
Is it possible to define a piecewise function, say b(x) and then use 'b(x)' in the function instead of an explicit function like 10x-100.
Hope someone can help me. Thanks in advance.
kind regards
Han Soethoudt

 Accepted Answer

Although it would be possible for fun1 to look at the x parameter to determine which value to use, if you do that then the ode* functions would either complain that the function had a singularity or else would give the wrong answer.
The ode* functions require that the function you provide is continuous itself, and is also continuous for its derivative (because the ode* functions use finite differences), and also that one more derivative beyond that is continuous (because of the mathematical models used to make predictions.)
Your approach of splitting the interval is the right approach.
Your code could look something like
function [t, f] = fun1_driver
b1 = @(x) ones(size(x));
b2 = @(x) 3 .* x + 4;
h0 = 1;
[tv1, f1] = ode23( @(x,h) fun1(x, h, b1), [0 10], h0);
h1 = f1(end,:);
[tv2, f2] = ode23( @(x,h) fun1(x, h, b2), [10 20], h1);
t = [tv1; tv2(2:end)]; %first point is x = 10 again
v = [f1; f2(2:end,:)]; %first point is x = 10 again
function f = fun1(x, h, b)
v = b(x);
f = (-(10*h)./v-0.001)./(((v.^2).*9.81.*h.^3./(1200.^2))-1);

1 Comment

Dear Walter, Thanks for the answer. It is not 100% what I hoped for to be possible, but it saves already a lot of time by putting b in a generic setting in ode. So, I'm grateful to your (quick) response ! kind regards Han Soethoudt

Sign in to comment.

More Answers (1)

f=@(x,h)(-(10*h)/b(x)-0.001)/(((b(x)^2)*9.81*h^3/(1200^2))-1);
b=@(x)10*x-100;
[tv1 f1]=ode23(f,[0 10],1);
b=@(x)3*x+4;
[tv2 f2]=ode23(f,[10 20],f1(end,1));
...
Best wishes
Torsten.

1 Comment

This will not work. Any variable that is not defined at the time of parsing the assignment to f will be marked as undefined, and assigning to the variable afterwards will not change that in the function handle. (The small details of this are expected to change in a later release.)

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!