Choosing isolines from Matlab contour function

纵然是瞬间 提交于 2019-11-30 16:06:41

问题


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.


回答1:


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:



来源:https://stackoverflow.com/questions/15301626/choosing-isolines-from-matlab-contour-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!