Solving 1D second order ODE BVP with dataset

92 Views Asked by At

I am solving a second-order ODE similar to the following equation: $$ y''+y=f(x), \\ y(0)=0,~~ y(π/2)=2, $$ xmesh = linspace(0,π/2,5);

If I use f(x) as a function of x such as x^2 or sin(x) or ... my code works and has no issue. However, in my case f(x) is a dataset in which its length is equal to the length of xmesh, and I cannot solve it. I am wondering if there is a way to use available MATLAB functions to solve my case. Here is my MATLAB code.

clear all
close all
clc

xmesh = linspace(0, pi/2, 5);
solinit = bvpinit(xmesh, @guess);

f = 2*xmesh;% I produce this dataset which is similar to my case

bvpfcn_x=@(x,y)[y(2);-y(1)+2*x];% {when I consider f=2x, there is no error and matlab calculate it.} 
%bvpfcn_x=@(x,y)[y(2);-y(1)+f];% when I consider f(x) as a dataset, then there is an error.

sol = bvp4c(bvpfcn_x, @bcfcn, solinit);
plot(sol.x, sol.y(1,:), '-o')

function res = bcfcn(ya,yb)% boundary conditions
  res = [ya(1);yb(1)-2];
end

function g = guess(x)% initial guess for y and y'
  g = [sin(x);cos(x)];
end
1

There are 1 best solutions below

6
On BEST ANSWER

You are given a function table, and you need a nice guess for values at arbitrary points as you do not control where the solver puts the mesh points, at least after the first mesh refinement. This task is widely known as interpolation. It would probably work best if you use a cubic spline interpolation, or even higher degree splines, as the solver uses a high-order collocation method that presupposes that the ODE is smooth of a similar order.