MATLAB: How to do Differential Equation Solution and plotting in matlab ? Please Help

differential equationsode45

I have written below matlab code for solving PDE. y” + 3y’ + 2y = P1,
Where;
P1(x) = [0 ; if x < 0
1 ; if 0 <= x <= 1
0] ; if x > 1
But it seems that it is not giving correct output. As well i want to plot solution over the interval [0, 2]. Can anyone help me how to modify function and how to plot ?
b1 = 1;
a1 = 1;
t = 0:0.1:5;
tspan = [0 5]
% a pulse function
% plot to
y0 = 0
y10 = 0
P1 = @(t,a,b) a*rectpuls(t,b)
[t, x] = ode45(@(t,x) Differential_Equation(t,y,a1,b1, y0,y10), tspan, y0)
plot(T,x);
function dy = Differential_Equation(t,y,a,b, y0, y10, P1)
% y'' + 3y' + 2y = P1
% y(0) = 0; y'(0) = 0
x = y(1);
v = y(2);
dy = zeros(2,1);
dy(1) = v;
dy(2) = (P1-3*dy(1) - 2*x)

Best Answer

Like so
b1 = 1;
a1 = 1;
%t = 0:0.1:5;
tspan = [0 5];
% a pulse function
% plot to
y0 = 0;
y10 = 0;
IC = [y0 y10]; % Initial conditions
P1 = @(t,a,b) a*rectpuls(t,b);
[t, x] = ode45(@(t,y) Differential_Equation(t,y,P1,a1,b1), tspan, IC);
plot(t,x);
function dy = Differential_Equation(t, y,P1,a1,b1)
% y'' + 3y' + 2y = P1
% y(0) = 0; y'(0) = 0
x = y(1);
v = y(2);
p1 = P1(t,a1,b1);
dy = zeros(2,1);
dy(1) = v;
dy(2) = (p1 - 3*v - 2*x);
end