0
votes

For example, if I have the following ODE: y''+y=0

In Matlab I could assume y(1)=y and y(2)=y', then

dy(1)=y(2)

dy(2)=-y(1)

Now, if I have the ODE in the form of y''+f(x)*y=0, where f(x) is a function that I can evaluate its numerical value anywhere but you don't have the analytical form and can't fit f(x) to a certain function. My question is then how to numerically solve this ODE in MATLAB if I want to put the value of f(x) in the ODE, for example,

f(x)=0.1 when x<0.5 and

f(x)=1.0 when x>=0.5

This ODE might be unrealistic but it gives an idea about the problem I am facing. Please don't solve it piecewise. Is that doable? Or I have to write the ODE solver by myself?

Thanks in advance for the inputs.

2
Are you trying to say that you just have data for f(x)? I assume that you have many more points than just two like in your example and that the data are discrete samples from an underlying smooth function? - horchler

2 Answers

0
votes

You can apply the same trick. Call y → y(1) and y' → y(2). Then

d/dx y(1) = y(2)

d/dx y(2) = - f(x) * y(1)

Implement a function

function dy = myodefun(x, y)
dy = zeros(2, 1);
dy(1) = y(2);
dy(2) = - f(x) * y(1);

or explicitly for your example

function dy = myodefun(x, y)
dy = zeros(2, 1);
dy(1) = y(2);
dy(2) = - (0.1 + (x >= 0.5) * 0.9) * y(1);

and give it to a standard solver, e.g. ode45.

0
votes

I myself found a solution to this question:

http://www.mathworks.com/help/matlab/ref/ode45.html?searchHighlight=interpolate

Interpolation has to be used. But seems like a feasible way.

Any other method is welcomed.