MATLAB: Unable to perform assignment because the left and right sides have a different number of elements.

left and right side

Hello, i tried to figure out where the problem is but i couldn't, can some one help me please
clear, clc, close
dT = 0.5;
T = 0:dT:8;
% Improved Euler method
Y1(1) = 1;
for i = 1:length(T)-1
k1 = Y1*(sin(T(i)))^3;
Y1(i+1) = Y1(i) + k1*dT;
k2 = Y1*(sin(T(i+1)))^3;
Y1(i+1) = Y1(i) + 0.5*( k1 + k2 )*dT;
end
plot(T, Y1, '-s')
% 4th order Runge-Kutta method
Y2(1) = 1;
for i = 1:length(T)-1
k1 = Y2*(sin(T(i)))^3;
y_star = Y2(i) + 0.5*k1*dT;
k2 = y_star*(sin((T(i)+0.5*dT)))^3;
y_star = Y2(i) + 0.5*k2*dT;
k3 = y_star*(sin((T(i)+0.5*dT)))^3 ;
y_star = Y2(i) + k3*dT;
k4 = y_star*(sin((T(i+1)))^3 ;
Y2(i+1) = Y2(i) + (1/6)*(k1 + 2*k2 + 2*k3 + k4)*dT;
end
plot(T, Y2, '-d')
% 2nd order Adams-Bashforth method
Y3(1) = 1;
Y3(2) = Y1(2);
% Calculate y(i+2) using the 2nd order Adams-Bashforth method
for i = 1:length(T)-2
k1 = Y3*(sin(T(i)))^3;
k2 = Y3*(sin(T(i+1)))^3 ;
Y3(i+2) = Y3(i+1) + 0.5*dT*(3*k2 - k1);
end
plot(T, Y3, '-p')
xlabel('t'), ylabel('y')
legend('Improved Euler', '4th order Runge-Kutta', '2nd order Adams-Bashforth')
end
plot(T, Y3, '-p')
xlabel('t'), ylabel('y')
legend('Improved Euler', '4th order Runge-Kutta', '2nd order Adams-Bashforth')

Best Answer

You have some missing indices in calculating some of the k1 and k2's. You also need to set hold on to get all three methods on the same graph. Try
dT = 0.5;
T = 0:dT:8;
% Improved Euler method
Y1(1) = 1;
for i = 1:length(T)-1
k1 = Y1(i)*(sin(T(i)))^3;
Y1(i+1) = Y1(i) + k1*dT;
k2 = Y1(i)*(sin(T(i+1)))^3;
Y1(i+1) = Y1(i) + 0.5*( k1 + k2 )*dT;
end
plot(T, Y1, '-s')
hold on
% 4th order Runge-Kutta method
Y2(1) = 1;
for i = 1:length(T)-1
k1 = Y2(i)*(sin(T(i)))^3;
y_star = Y2(i) + 0.5*k1*dT;
k2 = y_star*(sin((T(i)+0.5*dT)))^3;
y_star = Y2(i) + 0.5*k2*dT;
k3 = y_star*(sin((T(i)+0.5*dT)))^3 ;
y_star = Y2(i) + k3*dT;
k4 = y_star*sin((T(i+1)))^3 ;
Y2(i+1) = Y2(i) + (1/6)*(k1 + 2*k2 + 2*k3 + k4)*dT;
end
plot(T, Y2, '-d')
% 2nd order Adams-Bashforth method
Y3(1) = 1;
Y3(2) = Y1(2);
% Calculate y(i+2) using the 2nd order Adams-Bashforth method
for i = 1:length(T)-2
k1 = Y3(i)*(sin(T(i)))^3;
k2 = Y3(i)*(sin(T(i+1)))^3 ;
Y3(i+2) = Y3(i+1) + 0.5*dT*(3*k2 - k1);
end
plot(T, Y3, '-p')
xlabel('t'), ylabel('y')
legend('Improved Euler', '4th order Runge-Kutta', '2nd order Adams-Bashforth')