MATLAB: Euler’s method for two first order differential equations

euler methodfirst order differential equationsmultiple variables

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.

Best Answer

Try preallocating x and y
nsteps = (b-a)/h + 1; % this is the number of elements in t(a:h:b) (It is = N+1)
x=zeros(1,nsteps);
y=zeros(1,nsteps);
Also, when you define t as
t=a:h:b;
This creates a vector with T(1)=a and t(end)=b, so the following line
t(1)=a
is not necessary.
Inside your for loop, t has already been defined, above, as t=a:h:b, so you don't need to re-define it.
x and y need to be preallocated to size "nsteps", which is 1 greater than N, in order for your loop to work.
Related Question