MATLAB: How to extract x,y,z coordinates from a contour

contourextract xyz coordinates from a contour

Hi everybody,
I used the following codes to extract X,Y,Z coordinates from a contour. When I ran it in MATLAB 2013a, it works. But when I ran it in MATLAB 2016a, it doesn't work. I found that the codes is very sensitive to MATLAB version. Can anybody tell me how to solve this problem? Or are there any other MATLAB codes that serve the similar function? The code is from this link:

Best Answer

This works in R2017a, so it should also work for R2016a.
Example
f = @(x,y) x.^2 - y.^2; % Your Function
x = linspace(-10, 10); % X-Range
y = linspace(-10, 10); % Y-Range
[X,Y] = meshgrid(x,y); % Create Matrix Arguments
figure(1)
[C,h] = contour(X, Y, f(X,Y));
grid
Lvls = h.LevelList;
for k1 = 1:length(Lvls)
idxc{k1} = find(C(1,:) == Lvls(k1));
Llen{k1} = C(2,idxc{k1});
conturc{k1,1} = C(:,idxc{k1}(1)+1 : idxc{k1}(1)+1+Llen{k1}(1)-1);
conturc{k1,2} = C(:,idxc{k1}(2)+1 : idxc{k1}(2)+1+Llen{k1}(2)-1);
end
figure(2)
plot(conturc{3,1}(1,:), conturc{3,1}(2,:))
grid
The contour data now are a (2xN) vector created by horizontally concatenating the (x,y) coordinates of each contour line. The segments are created each as:
C = [Level x-coordinates; Length y-coordinates]
so the first column of each segment are the ‘Level’ and the ‘Length’ of the segment. The second output are the properties of the plot.
My code first plots the contour function, returning both outputs. It then uses the ‘LevelList’ property to return the plotted levels, and then uses these in the loop to find the start indices of the segments in the ‘C’ matrix in the ‘idxc’ cell array, and the number of elements in each contour segment in the ‘Llen’ cell array. It then uses these to extract the x (first row) and y (second row) coordinates for each contour segment in the ‘conturc’ cell array. The z-coordinates are the levels. They do not appear in the cell arrays, but correspond to the values in the ‘Lvls’ vector.
The plot in figure(2) is not necessary for the code. It shows how to get the data from the cell arrays (in this instance the third cell in the first group), and that the extracted values are correct.
This turned out to be an interesting adventure!