function [iik,ss]=elbow(VAR,nik)

% elbow  routine to apply elbow method and to select the optimal number of clusters.  
% [iik,ss]=elbow(VAR,nik)
%
% input:
% VAR  =       matrix of the variables to clustering
%             
% nik =        The number of iterations you want to apply, the method will iterate from 2 to nik.
%           
% output:
% iik     = an array that containts the number of clusters tested 
% ss      = an array that containts the sum of the squared of error (SSE)
%           of the distances of each object in the clusters from its centroid for
%           each number of clusters tested 
%   --------------------------------------------------------------------
%% Elbow method
% More information about this method can be found in (Ketchen & Shook, 1996)
% Ketchen, D. J., & Shook, C. L. (1996). The application of cluster analysis in strategic
% management research: An analysis and critique. Strategic Management Journal, 17(6), 441– 458.
% https://doi.org/10.1002/(SICI)1097-0266(199606)17:6<441::AID-SMJ819>3.0.CO;2-G
%   --------------------------------------------------------------------
%% Copyright notice
% Cite following references when you use this function.
%
% Odériz, I., Silva, R., Mortlock, T. R., Mori, N., Shimura, T., et al. (2021). 
% Natural variability and warming signals in global ocean wave climates. Geophysical
% Research Letters, 48, e2021GL093622. https://doi.org/10.1029/2021GL093622
%
% Odériz, I.,  Mori, N., Shimura, T., Webb, A., Silva, R., Mortlock, T. R., (2022). 
% Transitional Wave Climate Regions on Continental and Polar Coasts in a Warming World. Nature
% Climate Change

% Odériz, I., Mori, N., Shimura, T., Webb, A., Silva, R., Mortlock, T. R., Dataset for Transitional
% Wave Climate Regions on Continental and Polar Coasts in a Warming World (Version 1). Zenodo. DOI: 10.5281/zenodo.6482839 (2022).
%   --------------------------------------------------------------------
%       Itxaso Odériz
%       itxaso.oderiz@gmail.com	
%   --------------------------------------------------------------------
for ik=1:nik
[~,~,sumd, ~] = kmeans(VAR,ik); 
ss(ik)=sse(sumd);
end
iik=2:1:ik;
R=[iik',ss'];
save('kOptimo_Elbow.txt','R');
end