Euler's method for two first order differential equations?
Show older comments
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.
Accepted Answer
More Answers (1)
Eng
on 23 Apr 2023
0 votes
% 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')
Categories
Find more on Numerical Integration and Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!