Search code examples
matlabplotdifferential-equations

How to plot my differential equation with quiver?


I want to solve my differential equation and plot velocity vectors but I am having some trouble with that. I tried this:

syms y(x);
ode = (1+exp(x))*y*diff(y,x)-2*exp(x) == 0;
ySol = dsolve(ode)

[X,Y] = meshgrid(-2:.2:2);
Z = 2*exp(X)/((1+exp(X)).*Y);
[DX,DY] = gradient(Z,.2,.2);

figure
contour(X,Y,Z)
hold on
quiver(X,Y,DX,DY)
hold off

and I get this error:

Warning: Matrix is singular to working precision. 
Warning: Contour not rendered for non-finite ZData 

It is probably something simple that I do not see but I am just starting using Matlab and I cold not find a right way to do my task. Please help me...

EDIT

As bconrad suggested, I changed my Z function like this:

Z = 2*exp(X)/((1+exp(X)).*Y);

and the previous errors are fixed. However, my prime goal, to plot velocity vectors is not accomplished yet because I get a graph like this: enter image description here


Solution

  • Don’t have the ability to check at the moment, but I reckon you want an element by element division in that line. You’re missing a dot on the division, try

    Z = 2*exp(X)./((1+exp(X)).*Y);
    

    I took a closer look once at my station. The zero-division mentioned by Pablo forces inf's in Z, so quiver get's confused when scaling the vectors (understandably) and just doesn't show them. Try this (with the ode part removed):

    [X,Y] = meshgrid(-2 : .2 : 2);
    Z = 2 * exp(X) ./ ((1 + exp(X)) .* Y);
    Z(isinf(Z)) = nan; % To avoid 0-division problems
    [DX, DY] = gradient(Z, .2, .2);
    
    figure
    contour(X, Y, Z, 30, 'k')
    hold on
    quiver(X, Y, DX, DY, 6)
    hold off
    

    I've done 3 things here:

    1. Added the line Z(isinf(Z)) = nan; forcing infinite values to be essentially ignored by quiver
    2. Added the arguments 30, 'k' to the contour function to show 30 lines, and make them black (a bit more visible)
    3. Added the argument 6 to the quiver function. This overrides the automatic length-scaling of the vectors.

    You'll want to play with the arguments in the contour and quiver functions to make your figure appear as you'd like.

    PS: There is a handy arrow function on the file exchange that I find gives better control when creating vector field plots. See https://www.mathworks.com/matlabcentral/fileexchange/278-arrow - the ratings do it justice.