In: Mechanical Engineering
y'=y-x^2 ; y(1)= -4
My MATLAB program won't work. I am trying to get the main program to output a plot of the three equations (1 from the main program and two called in the function). The goal is to code a Euler method and a 2nd order Taylor numerical solution for
a. x0= 1.0 , step size h= 0.2, # of steps n=20
b. x0= 1.0 , step size h=0.05 , # of steps n=80 ; write a separate functionn for f(x,y) that is called. Plot the results on the same plot as the exact solution.
I keep getting an error of "Matrix Dimensions must agree ; error in Project_2(my function) with my Tay = ... equation (2nd order taylor equation).
Main Code
t_span = 1:0.2:5;
h=0.2;
y1 = -4;
B=(t_span.^2);
[x,y] = ode45(@(x,y) y-x^2, t_span, y1);
d=[x,y];
project_2(y1,h,d,B)
subplot(4,1,1)
plot(x,y)
xlabel('value of x')
ylabel('value of y(x)')
grid on
t_span = [1:0.05:5];
y1 = -4;
h=0.05;
[x,y]= ode45(@(x,y) y-x^2, t_span, y1);
subplot(4,1,4)
project_2(y1,h,d,B)
plot(x,y)
xlabel('value of x')
ylabel('value of y(x)')
grid on
The Function
function
[outputArg,Tay] = project_2(y1,h,d,B)
outputArg = y1 + h*d; %Euler method
Tay= y1 +(h*d)+((1/2)*(h^2))*((y1-2*t_span)+(-B)*d); %2nd order Taylor
subplot(4,1,2)
plot(outputArg)
subplot(4,1,3)
plot(Tay)
end
t_span = 1:0.2:5;
h=0.2;
y1 = -4;
B=(t_span.^2);
[x,y] = ode45(@(x,y) y-x^2, t_span, y1);
d=[x,y];
[outputArg,Tay] = project_2(y1,h,d,B,t_span);
subplot(3,2,1)
plot(x,y)
xlabel('value of x')
ylabel('value of y(x)')
grid on;
subplot(3,2,3)
plot(outputArg)
xlabel('no of points')
ylabel('outputArg')
grid on;
subplot(3,2,5)
plot(Tay)
xlabel('no of points')
ylabel('Tay')
grid on;
t_span = [1:0.05:5];
y1 = -4;
B=(t_span.^2);
h=0.05;
[x,y]= ode45(@(x,y) y-x^2, t_span, y1);
d = [x,y];
subplot(3,2,2)
project_2(y1,h,d,B,t_span)
plot(x,y)
xlabel('value of x')
ylabel('value of y(x)')
grid on;
subplot(3,2,4)
plot(outputArg)
xlabel('no of points')
ylabel('outputArg')
grid on;
subplot(3,2,6)
plot(Tay)
xlabel('no of points')
ylabel('Tay')
grid on;
function [outputArg,Tay] = project_2(y1,h,d,B,t_span)
outputArg = y1 + h.*d; %Euler method
Tay= y1 +(h.*d)+((1/2)*(h^2)).*((y1-2.*t_span')+(-B)'.*d); %2nd order Taylor
end