0

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.

Lexus00
  • 3
  • 1
  • 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 Jun 01 '15 at 22:25
  • 1
    possible duplicate of [Solving an ODE when the function is given as discrete values -matlab-](http://stackoverflow.com/questions/19732442/solving-an-ode-when-the-function-is-given-as-discrete-values-matlab) – horchler Jun 02 '15 at 16:03

2 Answers2

0

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.

A. Donda
  • 8,381
  • 2
  • 20
  • 49
  • Thanks A. Donda. But what it f(x) is a vector with, say, 1000 data points? In the example I provided f(x) can still be written into a function, but what if f(x) can not be be explicitly expressed as a function? – Lexus00 Jun 02 '15 at 04:37
  • Well you should have mentioned that in the question. They way you wrote it it seemed that you do have an implementation of `f(x)`. – A. Donda Jun 02 '15 at 19:06
0

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.

Lexus00
  • 3
  • 1