Search code examples
matlabmatlab-figurecontour

Contour plot using matlab fails


I am trying to make a contour plot using the following matlab code:

x=linspace(-10,10);
y=linspace(-10,10);
[X,Y]=meshgrid(x,y);
Z=X.^3-Y.^3;
figure
[c,h]=contour(X,Y,Z,[3]);
clabel(c,h)

This gives me the wrong picture actually: enter image description here

I really don't understand what goes wrong here, because when I do [c,h]=contour(X,Y,Z,[3 0]) for example, it does give me the correct contour plots for the levels 3 and 0, I need help.


Solution

  • If you only give a single number to contour there, it interprets it as the number of contour lines you want and picks the levels automatically. From the docs:

    contour(Z,v) draws a contour plot of matrix Z with contour lines at the data values specified in the monotonically increasing vector v. To display a single contour line at a particular value, define v as a two-element vector with both elements equal to the desired contour level. For example, to draw contour lines at level k, use contour(Z,[k k]). Specifying the vector v sets the LevelListMode property to manual.

    e.g. to get a single contour at "3", you need to do it this way instead:

    figure
    [c,h]=contour(X,Y,Z,[3,3]);
    clabel(c,h)