Tomer
Tomer

Reputation: 1704

Draw evenly-spaced height lines of a function in MATLAB

I would like to draw height lines of a function (represented by matrices, of course), using MATLAB.

I'm familiar with contour, but contour draws lines at even-spaced heights, while I would like to see lines (with height labels), in constant distance from one another when plotted.

This means that if a function grows rapidly in one area, I won't get a plot with dense height lines, but only a few lines, at evenly spaced distances.

I tried to find such an option in the contour help page, but couldn't see anything. Is there a built in function which does it?

Upvotes: 3

Views: 686

Answers (2)

Bas Swinckels
Bas Swinckels

Reputation: 18488

One thing you could do is, instead of plotting the contours at equally spaces levels (this is what happens when you pass an integer to contour), to plot the contours at fixed percentiles of your data (this requires passing a vector of levels to contour):

Z = peaks(100);  % generate some pretty data
nlevel = 30;

subplot(121)
contour(Z, nlevel)  % spaced equally between min(Z(:)) and max(Z(:))
title('Contours at fixed height')

subplot(122)
levels = prctile(Z(:), linspace(0, 100, nlevel));
contour(Z, levels);  % at given levels
title('Contours at fixed percentiles')

Result: enter image description here

For the right figure, the lines have somewhat equal spacing for most of the image. Note that the spacing is only approximately equal, and it is impossible to get the equal spacing over the complete image, except in some trivial cases.

Upvotes: 2

LowPolyCorgi
LowPolyCorgi

Reputation: 5188

There is no built-in function to do this (to my knowledge). You have to realize that in the general case you can't have lines that both represent iso-values and that are spaced with a fixed distance. This is only possible with plots that have special scaling properties, and again, this is not the general case.

This being said, you can imagine to approach your desired plot by using the syntax in which you specify the levels to plots:

...
contour(Z,v) draws a contour plot of matrix Z with contour lines at the data values specified in the monotonically increasing vector v.
...

So all you need is the good vector v of height values. For this we can take the classical Matlab exemple:

[X,Y,Z] = peaks;
contour(X,Y,Z,10);
axis equal
colorbar

enter image description here

and transform it in:

[X,Y,Z] = peaks;
[~, I] = sort(Z(:));
v = Z(I(round(linspace(1, numel(Z),10))));
contour(X,Y,Z,v);
axis equal
colorbar

enter image description here

The result may not be as nice as what you expected, but this is the best I can think of given that what you ask is, again, not possible.

Best,

Upvotes: 3

Related Questions