How do I plot/solve the phase portrait for functions with a range?

For example, if I have the following differential equation x'' = k
where k is equal to -r when x>0 r when x<0
How would I solve the above using ode45.
In this case there is a constant "r" (arbitrary), how would I use ode45 to solve that?
Shown below is my attempt at trying to at least form the graph of one equation (but I can't get MATLAB to reproduce the analytical solution). I'm quite new to this so any help would be appreciated.
f = @(t,y) [y(2);-r];
hold on
for y20=[0 0.2 0.4 0.6 2]
[ts,ys] = ode45(f,[0,20],[0;y20]);
plot(ys(:,1),ys(:,2))
end
hold off

 채택된 답변

Mischa Kim
Mischa Kim 2016년 10월 20일

1 개 추천

Afthab, see this answer.

댓글 수: 4

Unfortunately, this one doesn't help because I already have an idea on how to use the quiver function and how to repeat for multiple initial conditions. However, I don't know how to set up the differential equation for this problem because x'' = -r for x>0 and x'' = r for x<0
OK. Do you mean k=-r when t>0 or x>0?
Afthab
Afthab 2016년 10월 20일
편집: Afthab 2016년 10월 20일
x>0, so the solution should look something like this based on the hand analytical solution.
Gotcha. Try this:
function my_DE()
x0 = 0;
Dx0 = 0.2;
r = 1;
tspan = linspace(0,2,100);
options = odeset('RelTol',1e-8,'AbsTol',1e-10);
[~,X] = ode45(@DE, tspan,[x0; Dx0],options,r);
plot(X(:,1),X(:,2))
grid
end
function dX = DE(~,x,r)
dX = [x(2); k(x(1),r)];
end
function fval = k(x,r)
if (x < 0)
fval = +r;
else
fval = -r;
end
end
This needs some fine tuning.

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

추가 답변 (0개)

카테고리

태그

아직 태그를 입력하지 않았습니다.

질문:

2016년 10월 20일

댓글:

2016년 10월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by