function clusters=cosmo_clusterize(sample,nbrhood_mat)
% fast depth-first clustering based on equal values of neighbors
%
% clusters=cosmo_clusterize(ds,nbrhood,sizes)
%
% Inputs:
% ds A vector of size 1xN, or a dataset struct with a field
% .samples of size 1xN.
% nbrhood PxN neighborhood definition, if each feature has P
% neighbors at most. Values of zero can be used as
% fillers if a feature has less than P neighbors.
%
% Output:
% clusters 1xQ cell with cluster indices, if Q clusters are found.
% C{k} denotes the indices in ds that belong to the k-th
% cluster. Each value in C{k} is in the range 1:N.
%
% Example:
% % generate tiny fmri dataset with 6 voxels
% ds=cosmo_synthetic_dataset('ntargets',1,'nchunks',1);
% % compute neighborhood over voxels, so that two voxels are neighbors
% % if they share a vertex
% nh=cosmo_cluster_neighborhood(ds,'progress',false);
% %
% % set the data to be, when unflatten, a 2D matrix:
% % [-1 0 -1]
% % 3 0 -1]
% % with three clusters:
% % - linear index 1 (matrix element (1,1)) with element -1
% % - linear index 4 (matrix element (2,1)) with element 3
% % - linear indices 3 and 6 (matrix elments (:,3)) with element -1
% % Note that elements with indices:
% % - 1 and 4 are not neighbors because they have different values
% % - 1 and 3 are not neighbors because they are not connected, as the
% % neighborhood definition
% %
% ds.samples=[2 0 -1 3 0 -1];
% %
% % convert neighborhood definition to matrix form
% nh_mat=cosmo_convert_neighborhood(nh,'matrix');
% %
% % clusterize the data
% cl=cosmo_clusterize(ds.samples,nh_mat);
% %
% % show cluster indices
% cosmo_disp(cl)
% %|| { [ 1 ] [ 3 [ 4 ]
% %|| 6 ] }
%
% Notes:
% - Two features j and k are in the same cluster if:
% * their values ds(j) and ds(k) are the same (ds(j)==ds(k)),
% * features j and k are connected.
% Features j and k are connected if:
% * j==k, or
% % j and k are neigbors, or
% * there is a feature m, so that j and m are connected, and m and k
% are connected
% - Values of zero and NaN in ds are ignored for clusters.
%
% See also: cosmo_cluster_neighborhood, cosmo_convert_neighborhood
%
% # For CoSMoMVPA's copyright information and license terms, #
% # see the COPYING file distributed with CoSMoMVPA. #