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;endplot(t,x,'-',t,y,'--')
But there was an error saying
Unable to perform assignment because the left and right sides have a differentnumber 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