I am having a problem solving second order differential equation in matlab. The equation is: d2y/dx2=n-p; where n and p both are functions of x. Boundary conditions y(0)=0 and y(100)=0.8. When I try to solve using bvp4c it shows matrix dim must agree

8 views (last 30 days)
I am having a problem solving second order differential equation in matlab. The equation is:
d2y/dx2=n-p; where n and p both are functions of x.
Boundary conditions y(0)=0 and y(100)=0.8. When I try to solve using bvp4c it shows matrix dimensions must agree. I have understood the problem but dont know how to solve. My function
function yprime=bvpfunction(x,y)
yprime=[y(2);n-p]
%n and p are both functions of x.

Answers (1)

Walter Roberson
Walter Roberson on 11 Jan 2016
Edited: Walter Roberson on 11 Jan 2016
You do not have an 'end' matching your 'function' statement, so we know that your bvpfunction code cannot possibly be a nested function that might have access to a variable shared with a defining outer function.
We also know that you have no "global" statements that might import n or p.
The fact that you received an error about matrix dimensions instead of an error about undefined function or variable tells us that n and p must both somehow be defined anyhow.
From this we can deduce that your n and p are functions. And we can deduce that you are calling the functions without any input. In this situation, your code is equivalent to
yprime=[y(2);n()-p()]
and you are then running into problems because when you call n and p without input, the sizes of their outputs are not compatible with each other, or else the size of their output is not compatible with y(2)
Probably you want
yprime=[y(2);n(x)-p(x)]
  5 Comments
Walter Roberson
Walter Roberson on 11 Jan 2016
function yprime = bvpfunction(t, y, x, n, p)
napprox = interp1(x, n, t, 'linear', 'extrap');
papprox = interp1(x, p, t, 'linear', 'extrap');
yprime=[y(2); napprox - papprox];
and then in the place where you previously passed @bvpfunction to the ode routines, now pass
@(t, y) bvpfunction(t, y, x, n, p)
where x, n, p are the values you show.
Note: extrapolation outside of the table might not be very accurate, but if you cannot constrain the t range then you might need it. If you can constrain the t range then the 'extrap' should not do any harm; you could remove the 'extrap' if you are sure the t will always be within the x range.
Torsten
Torsten on 11 Jan 2016
>n and p are vectors with known x values
>x=linspace(0,100,100)
>sol1=bvp4c(@fun,@bc,bvpinit);
>sol2=bvp4c(@fun1,@bc1,bvpinit);
>n=sol1.y;
>p=sol2.y;
So you solve another two bvp's to get the values for n and p ?
In this case, you should solve all three bvps (for n, p and y) together to get higher efficiency and accuracy.
Best wishes
Torsten.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!