%Código modificado de https://github.com/isaacgerg/matlabHyperspectralToolbox

clc;clear;close all;

x=load('imagen_matriz.mat');
x=x.a;


endmember_number = 21;

M=x;
q=endmember_number;

%Se quita algunas bandas
M_real=M;
M(150:170,:)=[];
M(105:115,:)=[];
M(1:3,:)=[];

tic

M_orig = M;
M = hyperPct(M, q-1);
[p, N] = size(M);

% Initialize
U_idx = randperm(N,q); % Random endmember selection
E     = M(:,U_idx);    % Endmember matrix
V     = abs(det([ones(1,q); E])); % Simplex volume
vols  = zeros(q,1);



% Search for maximum volume simplex
for j = 1:N;
    % Replace each column of E with sample vector M(:,j) 
    % and compute the volume for each
    for k = 1:q;
        E_tmp      = E;
        E_tmp(:,k) = M(:,j);
        vols(k)    = abs(det([ones(1,q); E_tmp]));
    end
    % If max volume is greater than previous V, update E and V
    [V_tmp,k_idx] = max(vols);
    if V_tmp > V
        V            = V_tmp;
        E(:,k_idx)   = M(:,j);
        U_idx(k_idx) = j;
    end
end

% Return endmembers
M=M_orig;
M_orig=[zeros(3,314368); M(1:101,:); zeros(11,314368); M(102:135,:);zeros(21,314368);M(136:end,:)];
U = M_orig(:, U_idx);

toc

% Graficar

x_axis = linspace(0.4,2.5,224);

hold on;
for i=1:endmember_number
    plot(x_axis,U(:,i));
end

figure;
plot(x_axis,U(:,4));

title('Endmembers');
xlabel('Longitud de onda(um)');
ylabel('Reflactacia');
