MATLAB Answers

contourc - plotting contour matrix

175 views (last 30 days)
John Mahoney
John Mahoney on 1 Jun 2012
Edited: Nikola Stan on 26 Jan 2021
I would like to find the contours, manipulate them, and then plot them.
This plots contours
x = 0:0.1:1; y = 0:0.1:1;
[X,Y] = meshgrid(x,y);
Z = sin(X).*cos(Y);
[con_mat, h] = contour(x, y, Z);
To get the contour information without plotting, can use contourc.
con_mat = contourc(x, y, Z);
However, there appears to be no built-in way to plot this "contour matrix".
Any thoughts?


Sign in to comment.

Accepted Answer

Darin on 5 Jun 2012
Try this: it uses cplot, which you can find on Matlab central.
If you find something more elegant, please let us all know... it MUST be buried in the Matlab library function SOMEWHERE.
function[] = plot_contourmatrix(C);
% plot_countourmatrix - Plots a contour matrix c as returned from contour
% plot_contourmatrix(C)
% Rev History:
% 06-04-12 Created
holdstate = ishold;
hold on;
i = 1;
while i<=length(C)
lev = C(1,i);
cnt = C(2,i);
i = i+cnt+1;
if ~holdstate
hold off;
test code - execute as cell
[x,y] = meshgrid(-3:.1:3);
z = sinc(hypot(x,y));
[C,h] = contour(x,y,z);
axis equal
axis equal


John Mahoney
John Mahoney on 4 Dec 2014
Thanks Darin. I was using something similar, but was checking for integer values in C(2,:). This fails (almost never) when the y value is an integer. Yours does not have this problem.
It would be ideal to have a Matlab function not only for plotting this matrix, but for extracting the points in these contours (would use the same code as above.) as folks often want to process these contours before plotting etc.
Johannes Korsawe
Johannes Korsawe on 26 Jan 2015
Where to find cplot? it is not longer on the FEx ?

Sign in to comment.

More Answers (1)

Liviu Ivanescu
Liviu Ivanescu on 18 Aug 2018
Edited: Liviu Ivanescu on 18 Aug 2018
Here is a way to plot contourc data containing several contours of the same value.
cnt = contourc(matrix,[-2 -2]);
szc = size(cnt);
idz = 1;
while idz<szc(2)
izi = cnt(2,idz);
cnt(2,idz) = nan;
idz = idz+izi+1;

  1 Comment

Nikola  Stan
Nikola Stan on 26 Jan 2021
your example was useful to me. I added some code that allows it to keep different isolines separate, which is what I needed:
cnt = contourc(matrix,[-2 -2]);
szc = size(cntr);
idz = 1;
contourNo = 1;
while idz<szc(2)
izi = cntr(2,idz);
cntr(2,idz) = nan;
contourXY{contourNo} = cntr(:,idz+1:idz+izi);
idz = idz+izi+1;
contourNo = contourNo+1;
hold on
for k = 1:contourNo-1
plot(contourXY{k}(1,:), contourXY{k}(2,:));

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!