struggling with plotting slope field of second-order ODE containing sign function
11 views (last 30 days)
Show older comments
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!
Accepted Answer
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')
More Answers (0)
See Also
Categories
Find more on Vector Fields in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!