Search code examples
matlabplotdifferential-equations

Why my equation (y'=(3*x^3-y)/(3*x)) is not displaced properly with my plot functions?


I am trying to plot the solution of my differential equation but I can not get the correct graph with this method. According to Desmos, my function should look like this:

my function

This is my code:

clear
syms Y(X)
ode = diff(Y,X) == (3.*X.^3-Y)./(3.*X);
cond = Y(1) == 5;
YSol(X) = dsolve(ode, cond)
[X,Y] = meshgrid(-5 : .2 : 5);
Z = @(X,Y)(3.*X.^3-Y)./(3.*X);
dirfield(Z,-10:0.5:10,-10:0.5:10)
hold on;
[Xs,Ys] = ode45(Z,[-1,10],5); plot(Xs,Ys)
hold off

This is the function dirfield: 2

function dirfield(f,tval,yval)
% dirfield(f, t1:dt:t2, y1:dy:y2)
%   
%   plot direction field for first order ODE y' = f(t,y)
%   using t-values from t1 to t2 with spacing of dt
%   using y-values from y1 to t2 with spacing of dy
%
%   f is an @ function, or an inline function,
%     or the name of an m-file with quotes.
%
% Example: y' = -y^2 + t
%   Show direction field for t in [-1,3], y in [-2,2], use
%   spacing of .2 for both t and y:
%
%   f = @(t,y) -y^2+t
%   dirfield(f, -1:.2:3, -2:.2:2)

[tm,ym]=meshgrid(tval,yval);
dt = tval(2) - tval(1); 
dy = yval(2) - yval(1);
fv = vectorize(f);
if isa(f,'function_handle')
  fv = eval(fv);
end
yp=feval(fv,tm,ym); 
s = 1./max(1/dt,abs(yp)./dy)*0.35;
h = ishold;
quiver(tval,yval,s,s.*yp,0,'.r'); hold on;
quiver(tval,yval,-s,-s.*yp,0,'.r');
if h
  hold on
else
  hold off
end
axis([tval(1)-dt/2,tval(end)+dt/2,yval(1)-dy/2,yval(end)+dy/2])

Does anyone know what I did wrong? Thank you in advance.

EDIT:

The graph from Desmos has mixed axes but my problem is not there. I do not understand why I get this image:

image

instead of Desmos graph rotated counterclockwise (or something like that).

Maybie what I need is a different plot function?


Solution

  • This is a linear ODE of first degree with a singularity at x=0, there are no fold points away from the y axis. Indeed the solution is obtained by integrating

    (x^(1/3)*y)' = x^(7/3)
    

    so that

    (x^1/3)*y = 3/10*x^(10/3) + C  <==> y(x)  =  10/3*x^3 + C*x^(-1/3)
    

    with some expression containing large numbers for the integration constant C. This should also be the result if you print the result of dsolve.

    The graph you included is for a different problem.

    Or the graph has the axes exchanged, it is an y-x plot. For the initial condition y(1)=5 one gets C=5/3 and a graph that looks like that if mirrored on the diagonal.


    To plot the solution on both sides of the initial condition y(1)=5, you need to integrate and plot twice. Once for time range [1 5] and once for [1 0.1]. The maximal domain of the solution is (0,infinity), there is no solution and thus no graph for negative x. That would be a different solution, for instance for the initial condition y(-1)=-5.