Matlab code for ODE problems

조회 수: 10 (최근 30일)
Garrett Coss
Garrett Coss 2020년 10월 21일
답변: Pratyush Roy 2020년 10월 30일
I have the function (dy/dt)=-t*e^y, y(0)=0 and have to create a code using four seperate methods (Euler, Huen, Modified Euler, and RK4) in order to graph the four different method's y values from time t (-5,5) and 1 second intervals.
I created a code with each method however I cannot get them to work even individually let alone all together.
Any help would be appreciated.
clear all
close all
clc
k=1;
t=-5:k:5
y=zeros([11 1])
y(1)=1
n=numel(y)
% Euler Method
for i=1:n-1
y(i+1)=y(i)-t*exp(y(i))*k
end
% Huen Method
for i=1:n-1
fs=-t*exp(y(i))
yp(i+1)=y(i)-fs*k
fe=-t*exp(yp(i+1))
y(i+1)=y(i)+(1/2)*(fs+fe)*k
end
% Modifier Euler Method
for i=1:n-1
y(i+1/2)=y(i)-t*exp(y(i))*(k/2)
y(i+1)=y(i)-t*exp(y(i))*k
end
% RK4
for i=1:n-1
f1=-t*exp(y(i))
f2=-(t+k/2)*exp(y(i)+.5*f1*k)
f3=-(t+k/2)*exp(y(i)+.5*f2*k)
f4=-(t+k)*exp(y(i)+f3*k)
Qk=(1/6)*(f1+2*f2+2*f3+f4)
y(i+1)=y(i)+Qk*k
end
plot(t,y);
grid on

답변 (1개)

Pratyush Roy
Pratyush Roy 2020년 10월 30일
Hi Garrett,
For all the methods for solving ODEs, the time as well as variable should change in steps. Considering the code snippet for the Euler method:
y(i+1)=y(i)-t*exp(y(i))*k
The right hand side of the equation contains multiplication of y(i) with vector t which gives us a vector but that is assigned to a scalar value y(i+1).The time values should also vary in steps with the functional value y(i). The following code snippet demonstrates the case where both time and functional value is varying:
y(i+1)=y(i)-t(i)*exp(y(i))*k
The same changes are applicable for the other techniques as well.
Hope this helps!
Regards,
Pratyush.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by