The bivariate density can be computed using histcounts2. You'll need to specify either the number of bins or the bin edges for the x and y variables using one of the syntaxes below.
Here's what the solution will look like. xy is your nx2 matrix of [x,y] values.
[N,Xedges,Yedges] = histcounts2(xy(:,1), xy(:,2), 5);
Xcnt = Xedges(2:end) - abs(diff(Xedges(1:2))/2);
Ycnt = Yedges(2:end) - abs(diff(Yedges(1:2))/2);
figure()
contour(Xcnt,Ycnt, N)
xlim = [min(Xedges),max(Xedges)];
ylim = [min(Yedges),max(Yedges)];
arrayfun(@(x)xline(x,'Color',[.8 .8 .8]),Xedges)
arrayfun(@(y)yline(y,'Color',[.8 .8 .8]),Yedges)
cb = colorbar();
ylabel(cb,'density')
Best Answer