I have a problem with converting a differential equation into a function!!!

How to write y'+2*y=0 ; y(0)=1 as a function ?
I used the following but it did not work.
function f = eqn(x)
f=-2*x;
end
I need to plot the graph of this by using The Midpoint rule so I used the function recursively; however it did not plot it correctly, I think the problem is with the function above, my recursive method is also below there.(I don't think it has a problem!?)
function mid(func,y0,h,tf)
x=0:h:tf;
y(1)= y0;
for n = 2:length(x)-1
y(n+1)=y(n-1)+2*h*(feval(func,x(n)));
end
plot(x,y);
Thanks to everyone who can help me !

Answers (1)

hi,
You can this method first to confirm the result :
1) In M-file you create the function :
function dy=My_Function(t,y)
dy(1)=-2*y(1);
end
2) In the Command prompt, you solve the differential equation using Runge-Kutta algorithm :
[t,y]=ode23('My_Function',0,30,1);
plot(t,y) , xlabel(' Time (s)'), ylabel(' Magnitude');
title(' y''+2y=0');
Using your solution : The midpoint algorithm, try to verify this version :
h=0.05;
t=0:h:30;
y=zeros(size(t));
y(1)=1;
for n=1:length(t)-1
y(n+1)=y(n)*(1-h);
end
figure, plot(t,y)
axis([t(1) t(end) -0.2 1.2]), title(' MidPoint Technic')
Proof :
(y(n+1)-y(n))/h=-2y(n) ---> y(n+1)=y(n)*(1-h);
The solution gets better when the step resolution gets small, in this case h=0.05 .

4 Comments

By using this I can plot the exact soln. graph; however I still cannot get the midpoint rule graph which I need to see. Is there any way that I can use the recursive function I wrote with the M file you sent as an answer?
hi, i edited the answer, try that version and compare it with the Runge-Kutta algorithm
In the soln the graph seems correct; however I cannot see the ripple of the graph. I have to show that The mid-point rule is unstable.

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Asked:

on 9 Jul 2013

Community Treasure Hunt

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

Start Hunting!