codechimp
codechimp

Reputation: 1557

Matlab contour plot from contourc data

How, in Matlab, can I generate a contour plot from contour data such as that generated from countourc? contour uses, internally, contourc to convert elevation data to contour data; but it's not obvious from documentation how I might be able to simply provide the contour data directly.

Upvotes: 1

Views: 423

Answers (2)

saastn
saastn

Reputation: 6025

If you have many contour lines and want to plot all curves with same line properties, you can use the following function:

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) is borrowed from shade's answer, but it performs 30 times faster for my data since it calls plot/plot3 only once. This function plots each curve on its actual level, however, you can omit D(:, 3) and call plot for a flat contour. Use this like:

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

Upvotes: 1

shade
shade

Reputation: 161

Try this if you have older version of 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

This is for 2014 and newer

[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

Upvotes: 2

Related Questions