function p=minDist2points02(points, x0, showPlot) % minDist2points: Compute the point that has the min total distance to a set of points if nargin<2||isempty(x0), x0=mean(points, 2); end % Initial guess p=fminsearch(@(x)dist2pointsInner(x, points), x0); if showPlot && length(x0)==2 % ====== Create the objective function surface minValue=min(points, [], 2); maxValue=max(points, [], 2); x=linspace(minValue(1), maxValue(1), 51); y=linspace(minValue(2), maxValue(2), 51); zz=zeros(length(y), length(x)); for i=1:length(x) for j=1:length(y); zz(j,i)=dist2points([x(i), y(j)]', points); end end % ====== Mesh & contour plot subplot(121); h=meshc(x, y, zz); axis image; box on xlabel('X'); ylabel('Y'); zlabel('Z'); set(h(1), 'faceAlpha', 0.1); % Make the mesh transparent axisLimit=axis; line(p(1), p(2), axisLimit(5), 'marker', '.', 'color', 'r'); for i=1:size(points,2) line(points(1,i), points(2,i), axisLimit(5)*[1 1 1 1], 'marker', '.', 'color', 'k', 'markerSize', 20); end % ====== Detailed contour plot subplot(122); contour(x, y, zz, 100); axis image xlabel('X'); ylabel('Y'); zlabel('Z'); line(p(1), p(2), 'marker', '.', 'color', 'r', 'markerSize', 20); for i=1:size(points,2) line(points(1,i), points(2,i), 'marker', '.', 'color', 'k', 'markerSize', 20); end end function sumDistance=dist2pointsInner(x, points) % dist2points: The sum of distance sum to points sumDistance=0; for i=1:size(points,2) sumDistance=sumDistance+norm(x-points(:,i)); end