I have a problem with converting a differential equation into a function!!!
Afficher commentaires plus anciens
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 !
Réponses (1)
Youssef Khmou
le 9 Juil 2013
Modifié(e) : Youssef Khmou
le 9 Juil 2013
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 commentaires
Youssef Khmou
le 9 Juil 2013
Modifié(e) : Youssef Khmou
le 9 Juil 2013
hi, i edited the answer, try that version and compare it with the Runge-Kutta algorithm
Hasan
le 10 Juil 2013
Youssef Khmou
le 10 Juil 2013
try to change h to 0.95,0.75 .
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!