MATLAB: I need your help. y'(t) = -30*y+30*t^2+2*t; y(0)=1, & exact solution is y(t)=e^-30*x +x^2. i can’t understand what is different b/w kr4 plotting & its error . i need both graph n error please send me code.

function rungekutta123
h = 0.05;
t = 0;
w = 1;
fprintf('Step 0: t = %12.8f, w = %12.8f\n', t, w);
for i=1:50
k1 = h*f(t,w);
k2 = h*f(t+h/2, w+k1/2);
k3 = h*f(t+h/2, w+k2/2);
k4 = h*f(t+h, w+k3);
w = w + (k1+2*k2+2*k3+k4)/6;
t = t + h;
fprintf('Step %d: t = %6.4f, w = %18.15f\n', i, t, w);
end
%%%%%%%%%%%%%%%%%%
function v = f(t,y)
v = -30*y+30*t^2+2*t;

Best Answer

Are you trying to plot the result? If so, just save the integration step results in a matrix:
function rungekutta123
h = 0.05;
t = 0:0.05:2.5;
w(1) = 1;
fprintf('Step 0: t = %12.8f, w = %12.8f\n', t, w);
for ii=1:(length(t)-1)
k1 = h*f(t(ii),w(ii));
k2 = h*f(t(ii)+h/2, w(ii)+k1/2);
k3 = h*f(t(ii)+h/2, w(ii)+k2/2);
k4 = h*f(t(ii)+h, w(ii)+k3);
w(ii+1) = w(ii) + (k1+2*k2+2*k3+k4)/6;
fprintf('Step %d: t = %6.4f, w = %18.15f\n', ii, t(ii), w(ii));
end
y_exact = exp(-30.*t) + t.^2;
subplot(2,1,1)
plot(t,w,t,y_exact)
ylabel('Exact vs. approximated function')
subplot(2,1,2)
plot(t,w - y_exact)
ylabel('Error')
%%%%%%%%%%%%%%%%%%
function v = f(t,y)
v = -30*y+30*t^2+2*t;