MATLAB: I’m trying to do a Taylor series method for the equation y and compare it to the analytical solution. However, I keep getting a matrix dimension error. any help would be much appreciated.

differentiationMATLABtaylor series

t = 0:0.1:2; %h = 0.1%
h = 0.1;
y = (-cos(4*t))./4 - 0.5;
z = (-cos(0))./4 - 0.5;
y1 = diff(y);
y2 = diff(y,2);
y3 = diff(y,3);
y4 = diff(y,4);
taylor_y = (z + (h.*y1) + ((h^2/factorial(2)).*y2) + ((h^3/factorial(3)).*y3) + ((h^4/factorial(4)).*y4));
fig = figure();
set(fig,'color','white');
plot(t,y,'LineWidth',2)
grid on
xlabel('t')
ylabel('y')
hold on
plot(t,taylor_y,'r','LineWidth',2)

Best Answer

Using diff reduces the dimension of the array by 1. You check the dimensions of y1, y2, y3, y4..they are of size 1X20, 1X19, 1x18, 1x17 respectively. Instead of suing diff you can striaght away use the differentiation of y.
t = 0:0.1:2; %h = 0.1%
h = 0.1;
y = (-cos(4*t))./4 - 0.5;
z = (-cos(0))./4 - 0.5;
y1 = 4*sin(4*t) ;
y2 = 16*cos(4*t) ;
y3 = -64*sin(4*t) ;
y4 = 256*cos(4*t) ;
taylor_y = (z + h*y1 + ((h^2/factorial(2))*y2) + ((h^3/factorial(3))*y3) + ((h^4/factorial(4))*y4));
fig = figure();
set(fig,'color','white');
plot(t,y,'LineWidth',2)
grid on
xlabel('t')
ylabel('y')
hold on
plot(t,taylor_y,'r','LineWidth',2)