%% Determine Similarity of Endmember Spectra Using SAM
% Read hyperspectral data into the workspace.

hcube = hypercube('indian_pines.dat');

% Find ten endmembers of the hyperspectral data.

numEndmembers = 10;
endmembers = nfindr(hcube,numEndmembers);

% Consider the first endmember as the reference spectra and the rest of the endmembers as the test spectra. Compute the SAM score between the reference and test spectra.

score = zeros(1,numEndmembers-1);
refSpectra = endmembers(:,1);
for i = 2:numEndmembers
    testSpectra = endmembers(:,i);
    score(i-1) = sam(testSpectra,refSpectra);
end

% Find the test spectra that exhibit maximum similarity (minimum distance) to the reference spectra. Then find the test spectra that exhibit minimum similarity (maximum distance) to the reference spectra.

[minval,minidx] = min(score);
maxMatch = endmembers(:,minidx);
[maxval,maxidx] = max(score);
minMatch = endmembers(:,maxidx);

% Plot the reference spectra, the maximum similarity and the minimum similarity test spectra. The test spectra with the minimum score value indicates highest similarity to the reference endmember. On the other hand, the test spectra with the maximum score value has the highest spectral variability and characterises the spectral behaviour of two different materials.

figure
plot(refSpectra)
hold on
plot(maxMatch,'k')
plot(minMatch,'r')
xlabel('Band Number')
ylabel('Data Values')
legend('Reference spectra','Minimum match test spectra','Maximum match test spectra',...
       'Location','Southoutside')
title('Similarity Between Spectra')
annotation('textarrow',[0.25 0.25],[0.4 0.5],'String',['Max score: ' num2str(maxval)])
annotation('textarrow',[0.6 0.55],[0.6 0.45],'String',['Min score: ' num2str(minval)])

% Copyright 2020 The MathWorks, Inc.