Badshah
Badshah

Reputation: 431

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.

Upvotes: 0

Views: 690

Answers (2)

nkjt
nkjt

Reputation: 7817

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)

Upvotes: 1

Ander Biguri
Ander Biguri

Reputation: 35525

The fourth argument of contour can be two things.

If it is an array of numbers (more than 1) then its the contour value you want to show. Else, if its a single value, its the amount of contour lines you want to show.

Example:

x=linspace(-10,10);
y=linspace(-10,10);
[X,Y]=meshgrid(x,y);
Z=X.^3-Y.^3;
figure
subplot(121)
[c,h]=contour(X,Y,Z,[10]);
clabel(c,h)
subplot(122)
[c,h]=contour(X,Y,Z,[1000 -1000 50 -70 3 0]);
clabel(c,h)

enter image description here

Upvotes: 1

Related Questions