MATLAB: Help with bvp4c error

add vectorbvp4cMATLAB

Hello, I am struggling with a problem, which I am not sure if possible to solve with bvp4c. Since my problem involves many long equations, I will use a modified example from the MATLAB manual to illustrate it.
So let us say that I want to solve the system: y'' = -|y| + G(x) where the solution of G(x) is known, but its form is not. I.e., for x = [0 0.4 … 4], G(x) = [0 0.4 … 4]. In this example I have used G(x) = x for simplicity, however in my real problem it is a numerical solution from another bvp.
Here is the Code:
function test()
x = linspace(0,4,11);
Gx = [0 0.4 0.8 1.2 1.6 2 2.4 2.8 3.2 3.6 4]
solinit = bvpinit(x,[1 0]);
sol = bvp4c(@twoode,@twobc,solinit);
y = deval(sol,x);
plot(x,y(1,:))
function dydx = twoode(x,y)
dydx = [ y(2,:); -abs(y(1,:)) + Gx ];
end
function res = twobc(ya,yb)
res = [ ya(1); yb(1) + 2 ];
end
end
When I run it, I get the error:
Error using vertcat
Dimensions of matrices being concatenated are not consistent.
Error in test/twoode (line 12)
dydx = [ y(2,:); -abs(y(1,:)) + Gx ];
Error in bvparguments (line 105)
testODE = ode(x1,y1,odeExtras{:});
Error in bvp4c (line 130)
bvparguments(solver_name,ode,bc,solinit,options,varargin);
Error in test (line 7)
sol = bvp4c(@twoode,@twobc,solinit);
I have also tried to transpose G(x). Then I get the error:
Error using bvparguments (line 108)
Error in calling BVP4C(ODEFUN,BCFUN,SOLINIT):
The derivative function ODEFUN should return a column vector of length 2.
Error in bvp4c (line 130)
bvparguments(solver_name,ode,bc,solinit,options,varargin);
Error in test (line 7)
sol = bvp4c(@twoode,@twobc,solinit);
I will appreciate any suggestions or comments.

Best Answer

function test()
x_global = linspace(0,4,11);
Gx_global = [0 0.4 0.8 1.2 1.6 2 2.4 2.8 3.2 3.6 4]
solinit = bvpinit(x_global,[1 0]);
sol = bvp4c(@(x,y)twoode(x,y,x_global,Gx_global),@twobc,solinit);
y = deval(sol,x_global);
plot(x_global,y(1,:))
function dydx = twoode(x,y,x_global,Gx_global)
Gx = interp1(x_global,Gx_global,x);
dydx = [ y(2); -abs(y(1)) + Gx ];
end
function res = twobc(ya,yb)
res = [ ya(1); yb(1) + 2 ];
end
end