Euler's method for two first order differential equations?
이전 댓글 표시
I was trying to solve two first order differential equations like below using the Euler's method and plot two graphs with x and y as a function of t.
The differential equations are:
dxdt = @(x,t) -1.*y-0.1.*x;
dydt = @(y,t) x-0.5.*y;
I tried this script below:
a=0; %initial time
b=2000; %final time
h = 0.01; % time step
N = (b-a)./h;
t=a:h:b;
t(1)=a;
x(1)=0;
y(1)=0;
dxdt = @(x,t) -1.*y-0.1.*x;
dydt = @(y,t) x-0.5.*y;
for n=1:N
x(n+1)=x(n)+h.*dxdt(x(n),t(n));
y(n+1)=y(n)+h.*dydt(y(n),t(n));
t(n+1)=a+n*h;
end
plot(t,x,'-',t,y,'--')
But there was an error saying
Unable to perform assignment because the left and right sides have a different
number of elements.
Error in Q6 (line 15)
x(n+1)=x(n)+h.*dxdt(x(n),t(n));
I did not quite understand why.
Could anyone help me with this please?
Thanks in advance.
채택된 답변
추가 답변 (1개)
Eng
2023년 4월 23일
0 개 추천
% Define the differential equation dydx = @(x,y) x + y;
% Define the initial condition y0 = 1;
% Define the step size and interval h = 0.1; x = 0:h:1;
% Initialize the solution vector y = zeros(size(x)); y(1) = y0;
% Apply the Modified Euler Method for i = 1:length(x)-1 k1 = dydx(x(i), y(i)); k2 = dydx(x(i+1), y(i)+hk1); y(i+1) = y(i) + h/2(k1+k2); end
% Plot the solution plot(x,y) xlabel('x') ylabel('y')
카테고리
도움말 센터 및 File Exchange에서 Numerical Integration and Differential Equations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
