来自 contourc 数据的 Matlab 等高线图

Matlab contour plot from contourc data

如何在 Matlab 中从 等值线数据 生成等值线图,例如从 countourc 生成的等值线图? contour 在内部使用 contourc 将高程数据转换为等高线数据;但从文档中看不出我如何能够直接提供等高线数据。

如果你有旧版本的 MATLAB,试试这个

[C,h] = contour(peaks(30),-8:2:8);
h1 = get(h,'children');
X = get(h1,'xdata');
Y = get(h1,'ydata');
hold on
plot(X{5},Y{5},'.r')
hold off

这是 2014 年及以后的版本

[C,h] = contour(peaks(30),-8:2:8);
i = 1;
slev = 4;                           % draw specific level
hold on
while i < size(C,2)
    ncnt = C(2,i);                  % number of points for current contour
    if abs(C(1,i) - slev) < 0.01    % check if it's desired contour
        icnt = i+(1:ncnt);
        plot(C(1,icnt), C(2,icnt), '.r')
        break;
    end
    i = i + ncnt + 1;               % next contour
end
hold off

如果你有很多等高线并且想要绘制所有具有相同线属性的曲线,你可以使用以下函数:

function h = contourC(C, varargin)
i = 1;
D = [C.' zeros(size(C, 2), 1)];
while (i < size(C,2))
    lvlv = C(1, i);                 % level value
    ncnt = C(2, i);                 % number of points for current contour
    D(i:i+ncnt, 3) = lvlv;
    D(i, :) = NaN;
    i = i + ncnt + 1;               % next contour
end
h = plot3(D(:, 1), D(:, 2), D(:, 3), varargin{:});
end

Parsing ContourMatrix (C) 是从 shade 的答案中借用的,但它对我的数据执行速度快 30 倍,因为它只调用一次 plot/plot3。 此函数在其实际水平上绘制每条曲线,但是,您可以省略 D(:, 3) 并调用 plot 以获得平坦轮廓。像这样使用:

C = contourc(data, ...);
h = contourC(C, '-k', 'linewidth', 1);