The Matlab contour function (and imcontour) plots isolines of different levels of a matrix. I would like to know: How can I manipulate the output of this function in order to receive all the (x,y) coordinates of each contour, along with the level? How can I use the output [C,h] = contour(...) to achieve the aforementioned task? Also, I am not interested in manipulating the underlying grid, which is a continuous function, only extracting the relevant pixels which I see on the plot.
Asked
Active
Viewed 9,672 times
4
-
"Difficult to work with" and "not straightforward" doesn't disqualify a solution. Just go with it. If you have problems, re-ask your question with the problems you are actually having. – Peter Mar 08 '13 at 19:33
1 Answers
5
You can use this function. It takes the output of the contour
function, and returns a struct array as output. Each struct in the array represents one contour line. The struct has fields
v
, the value of the contour linex
, the x coordinates of the points on the contour liney
, the y coordinates of the points on the contour linefunction s = getcontourlines(c)
sz = size(c,2); % Size of the contour matrix c ii = 1; % Index to keep track of current location jj = 1; % Counter to keep track of # of contour lines while ii < sz % While we haven't exhausted the array n = c(2,ii); % How many points in this contour? s(jj).v = c(1,ii); % Value of the contour s(jj).x = c(1,ii+1:ii+n); % X coordinates s(jj).y = c(2,ii+1:ii+n); % Y coordinates ii = ii + n + 1; % Skip ahead to next contour line jj = jj + 1; % Increment number of contours end
end
You can use it like this:
>> [x,y] = ndgrid(linspace(-3,3,10));
>> z = exp(-x.^2 -y.^2);
>> c = contour(z);
>> s = getcontourlines(c);
>> plot(s(1).x, s(1).y, 'b', s(4).x, s(4).y, 'r', s(9).x, s(9).y, 'g')
Which will give this plot:

h k
- 320
- 2
- 13

Chris Taylor
- 46,912
- 15
- 110
- 154
-
Excellent answer, the example along with the plot make everything very clear (-: – Leeor Mar 09 '13 at 07:54
-
There is a typo in this line: `z = exp(-x.^2 -y,^2);` You probably would want to replace `,` with `.` here. Apart from that, I don't know how `#` and `%` used to look 4 years ago but now the text following `%` appears in grey color and seems decent or it could be just me!! – Sardar Usama Feb 04 '17 at 12:18