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

hcube = hypercube('jasperRidge2_R198.hdr');

% Find 10 endmembers of the hyperspectral data cube by using the N-FINDR method.

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 SID 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) = sid(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, maximum similarity test spectra, and the minimum similarity test spectra. The test spectra with the minimum score has the highest similarity to the reference endmember. On the other hand, the test spectra with maximum score 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')
legend('Reference spectra','Minimum match test spectra','Maximum match test spectra',...
       'Location','Southoutside');
title('Similarity Between Spectra')
annotation('textarrow',[0.3 0.3],[0.4 0.52],'String',['Min score: ' num2str(minval)])
annotation('textarrow',[0.6 0.6],[0.4 0.55],'String',['Max score: ' num2str(maxval)])
xlabel('Band Number')
ylabel('Data Values')

% Copyright 2020 The MathWorks, Inc.