ODE Piecewise Linear Function Help

Not sure what's wrong but this is what I have to do:
The listing of a Matlab script file which uses dsolve() to solve the following ODE and plot the results from t=0 to t=3. dx/dt + 2 x = f(t) with x(0) = 1 and where
f(t) = exp(-t) 0 <= t <= ln(2) f(t) = 4 for ln(2) < t <=ln(3) f(t) = 0 otherwise
SHOW: The output generated by the script file The plot generated by the script file
THIS IS WHAT I HAVE..
+++++++++++++++++++++++++++++
%last modified: 2/27/2014
%Matlab
%for piecewise continuous input
%of first order linear systems
clear all
clc
format compact
% Example
% dx/dt + 2x = f(t)
% f(t) = 1 for 0<=t<=1 and 0 otherwise
% Symbolic approach
% Find x in the first interval
% Note the use of pure symbolics instead
% of a character string solution like
% x1 = dsolve('Dx1+x1=1','x1(0)=0')
syms t x1(t)
dx1 = diff(x1);
t = 1;
x1 = dsolve(dx1+2*x1==exp(-t), x1(0)==1);
display(['x1 = ', char(vpa(x1,3))])
%Use solutions for first interval to find
%IC for second interval
x2_IC = subs(x1);
display(['x2_IC = ', char(vpa(x2_IC,3))])
%Find solution in second interval using
%x2_IC as an IC
syms t x2(t)
dx2 = diff(x2);
x2 = dsolve(dx2+2*x2==4, x2(log(2))==x2_IC);
x3_IC = subs(x2);
display(['x3_IC = ', char(vpa(x3_IC,3))])
syms x3(t)
dx3 = diff(x3);
x3 = dsolve(dx3+2*x3==0, x3(log(3))==x3_IC);
display(['x3 = ', char(vpa(x3,3))])
%Plot the results
t = 0:0.01:1;
xx1 = subs(x1);
plot(t,xx1,'linewidth', 3,'color','red')
t = 1:0.01:3;
xx2 = subs(x2);
plot(t,xx2,'linewidth',3,'color','green')
t = 3:0.01:5;
xx3 = subs(x3);
hold on
plot(t,xx3,'linewidth',3,'color','blue')
grid on
xlabel('t','FontSize',14)
ylabel('x','FontSize',14)
title('x vs time','FontSize',14)
hold off

2 个评论

Do you need to solve it using symbolic math (rather than doing it numerically)?
Actually, either one is okay..

请先登录,再进行评论。

 采纳的回答

In this case have a look at:
function my_DE()
x0 = 1;
tspan = linspace(0,3,1000);
[T,X] = ode45(@DE, tspan, x0);
plot(T,X)
grid
end
function dX = DE(t,x)
dX = -2*x + f(t);
end
function fval = f(t)
if (t <= log(2))
fval = exp(-t);
elseif (t > log(2)) && (t <= log(3))
fval = 4;
else
fval = 0;
end
end
...not including the color coding in the plot.

2 个评论

Nice! Thanks a lot Mischa!
Mischa, how would I do this using symbolic math?

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Number games 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by