Leeor
Leeor

Reputation: 637

Choosing isolines from Matlab contour function

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.

Upvotes: 4

Views: 9847

Answers (1)

Chris Taylor
Chris Taylor

Reputation: 47392

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 line
  • x, the x coordinates of the points on the contour line
  • y, the y coordinates of the points on the contour line

    function 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:

enter image description here

Upvotes: 5

Related Questions