struggling with plotting slope field of second-order ODE containing sign function

14 views (last 30 days)
Hello, I am trying to plot the slope field of a second-order differential equation containing sign function: x'' + sgn(x) = 0 and its trajectory when x(0) = 1 and x'(0)=2. Howerver, it seems that the plot of trajectory doesn't align with the slope field figure. Here is my codes:
%Plot direction field:
% (I just imitate from someone's codes of plotting slope field of
% x''+5x'+4x=0, I guess I can directly substitute 0x' into 5x' and sign(x)
% into 4x)
xdom = linspace(-2,2,25);
ydom = linspace(-2,2,25);
[X,Y] = meshgrid(xdom,ydom);
U = Y;
V = (-0*Y - sign(X));
quiver(X,Y,U,V,'r')
%Plot the trajectory:
syms x(t)
Dx = diff(x)
ode = diff(x,t,2) == -sign(x)
cond1 = x(0) == 1
cond2 = Dx(0) == 2
conds = [cond1 cond2]
xSol = dsolve(ode,conds)
ezplot(xSol)
I have no idea why this problem happens, but I guess the slope field is wrong and I don't know how to make it right. Could anyone help me point out what's wrong with my codes? Thank you so much!
  2 Comments
Jiri Hajek
Jiri Hajek on 12 Jan 2023
Hi, note that slope field is meaningful only for a first-order ODE, where it gives you a "feel" for its solutions. In your case, as you have a second order ODE, so you don't have this possibility. Note however, that once you have the solution, you can use its first derivative of your solution to create a slope field.
Kieth Duong
Kieth Duong on 13 Jan 2023
Yes I am clear of that, but I learn that we can transform a second-order ode into a system of 1st-order ode so I want to give a try. But anw thanks for letting me know!

Sign in to comment.

Accepted Answer

Sam Chak
Sam Chak on 12 Jan 2023
The slope field depends on how the mesh is generated. Denser mesh is more accurate but with quiver, it will produce thousands of tiny quivers, rendering the plot uninterpretable. Try something like this.
xdom = linspace(-4, 4, 20);
ydom = linspace(-4, 4, 20);
[X, Y] = meshgrid(xdom, ydom);
U = Y;
V = - sign(X);
quiver(X, Y, U, V)
hold on
odefcn = @(t, x) [x(2); - sign(x(1))];
tspan = linspace(0, 50, 5001)';
x0 = [1 2];
[t, x] = ode15s(odefcn, tspan, x0);
plot(x(:,1), x(:,2)), grid on, xlim([-4 4]), ylim([-4 4])
xlabel('x_1'), ylabel('x_2')
hold off
plot(t, x), grid on, ylim([-5 5])
xlabel('t'), legend('x_1', 'x_2')
  4 Comments
Sam Chak
Sam Chak on 13 Jan 2023
Hi @Kieth Duong, feel free to code some special ODEs known as the chaotic oscillators.
One of the most popular ones is the Lorenz system.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!