% MATLAB program to find the minimum enclosing circle of a point set
% fminsearch uses the Nelder-Mead algorithm
% https://se.mathworks.com/help/optim/ug/fminsearch-algorithm.html

global x y trace_x trace_y

x = [1.0, 3.0, 2.5, 4.0, 5.0, 6.0, 5.0];
y = [3.0, 1.0, 3.0, 6.0, 7.0, 7.0, 2.0];
trace_x = [];
trace_y = [];

c = fminsearch(@(x) max_distance(x), [0,0]);

hold on
plot(x, y, "o", 'color', 'b', 'MarkerFaceColor', 'b'); 
plot(trace_x, trace_y, "*-", "color", "g");
plot(c(1), c(2), "o", 'color', 'r', 'MarkerFaceColor', 'r'); 
viscircles(c, max_distance(c),"color","red");

function dist = max_distance(p)
    global x y trace_x trace_y
    
    trace_x = [trace_x, p(1)];
    trace_y = [trace_y, p(2)];
    dist = 0.0;
    for i=1:length(x)
        dist = max(dist, pdist([p; x(i), y(i)], 'euclidean' ));
    end
end