Finding a 2D area defined by contour lines in Matlab

I find it difficult to calculate the 2D region of the contours obtained from the kernel density estimate (KDE) in Matlab. I have three variables:

X and Y = meshgrid, which calculates the variable "density" (256x256) density = density calculated from KDE (256x256)

I am running the code

contour (X, Y, density, 10)

This leads to the application. For each of the 10 levels of the contour, I would like to calculate the area. I did this on some other platforms, such as R, but it's hard for me to understand the correct method / syntax in Matlab.

C = contour (density)

I believe that the above line will save all the values ​​of the contours, allowing me to calculate the area, but I do not quite understand how these values ​​are stored and how to get them correctly.

! .

+4
2

script . contour. , contour3 contourf, , .

[X,Y,Z] = peaks;   %example data
% specify certain levels
clevels = [1 2 3];
C = contour(X,Y,Z,clevels);
xdata = C(1,:);   %not really useful, in most cases delimters are not clear
ydata = C(2,:);   %therefore further steps to determine the actual curves:

%find curves
n(1) = 1;         %n: indices where the certain curves start
d(1) = ydata(1);  %d: distance to the next index
ii = 1;
while true

       n(ii+1) = n(ii)+d(ii)+1;    %calculate index of next startpoint

       if n(ii+1) > numel(xdata)   %breaking condition
           n(end) = [];            %delete breaking point
           break
       end

       d(ii+1) = ydata(n(ii+1));   %get next distance
       ii = ii+1; 
end

%which contourlevel to calculate?
value = 2;             %must be member of clevels
sel = find(ismember(xdata(n),value));
idx = n(sel);          %indices belonging to choice
L = ydata( n(sel) );   %length of curve array

% calculate area and plot all contours of the same level
for ii = 1:numel(idx)
    x{ii} = xdata(idx(ii)+1:idx(ii)+L(ii));
    y{ii} = ydata(idx(ii)+1:idx(ii)+L(ii));

    figure(ii)
    patch(x{ii},y{ii},'red');            %just for displaying purposes
    %partial areas of all contours of the same plot
    areas(ii) = polyarea(x{ii},y{ii});   

end

% calculate total area of all contours of same level
totalarea = sum(areas)

: ( Matlab)

value=2 - , , . .

enter image description here


, , . , , . , contourmatrix , . , contour, C , xdata ydata polyarea

+2

, Matlab (...).

- .

c = contour(X,Y,density,10)

c , .

+2

All Articles