close all; clear; clc;

%%
rng('shuffle');
seed = round(1e6*rand);
seed = 593772;
rng(seed); % 25815

A = rand(3,3); A = 1.5*eye(3) + A*A'; % Positive semi-definite matrix

%% Eigenvalues with eig
tic
[V,D] = eig(A);
toc

%% Eigenvalues by optimisation
lossfun_1 = @(L) log10( det(A - (L)*eye(3)).^2 );
options = optimset('Display','none');
tic
d1 = fminsearch(lossfun_1,0,options);
lossfun_2 = @(L) lossfun_1(L) + log10( (L-d1).^-2 );
d2 = fminsearch(lossfun_2,d1,options);
lossfun_3 = @(L) lossfun_2(L) + log10( (L-d2).^-2 );
d3 = fminsearch(lossfun_3,d2,options);
toc

%%
D_eig = diag(D)';
D_optim = sort([d1 d2 d3]);

clear L1 L2 L3
Ls = linspace(0,7,301);
for v1i = 1:numel(Ls)
    L1(v1i) = lossfun_1(Ls(v1i));
    L2(v1i) = lossfun_2(Ls(v1i));
    L3(v1i) = lossfun_3(Ls(v1i));
end

%% Plot
figure(1); clf;
plot(Ls,L1,Ls,L2,Ls,L3);
xlim([0 7]); ylim([-5 4]);
grid on; axis square;
xlabel('L'); ylabel('optimfun');
drawnow;

plot(Ls,L1,Ls,L2,Ls,L3);
xlim([0 7]); ylim([-5 4]);
grid on; axis square;
xlabel('L'); ylabel('optimfun');