ODE Piecewise Linear Function Help

조회 수: 1 (최근 30일)
Braulio Diaz
Braulio Diaz 2014년 2월 27일
편집: Walter Roberson 2019년 8월 31일
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
Mischa Kim
Mischa Kim 2014년 2월 27일
Do you need to solve it using symbolic math (rather than doing it numerically)?
Braulio Diaz
Braulio Diaz 2014년 2월 27일
편집: Braulio Diaz 2014년 2월 27일
Actually, either one is okay..

댓글을 달려면 로그인하십시오.

채택된 답변

Mischa Kim
Mischa Kim 2014년 2월 27일
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
Braulio Diaz
Braulio Diaz 2014년 2월 27일
Nice! Thanks a lot Mischa!
Braulio Diaz
Braulio Diaz 2014년 2월 27일
Mischa, how would I do this using symbolic math?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Equation Solving에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by