Last active
August 29, 2015 14:07
-
-
Save tonyfast/2082377134303a55dbc6 to your computer and use it in GitHub Desktop.
A simple clustering function that uses graph power for connectivity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| %% Example use of simplecluster | |
| X = rand(20,2); | |
| cutoff = .1; | |
| [ Xf, class ] =simplecluster( X, cutoff ); | |
| h(1) = scatter( X(:,1), X(:,2), 50, class, 'filled'); | |
| set(h(1), 'MarkerEdgeColor','k') | |
| hold on | |
| h(2) = plot( Xf(:,1), Xf(:,2), 'k+', ... | |
| 'Markersize', 14 ); | |
| grid on | |
| hold off | |
| title( sprintf('Points Connected within %f units', cutoff) , 'FontSize', 14 ) | |
| legend( h, 'Original', 'Clustered' ) | |
| axis equal | |
| axis square | |
| figure(gcf) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function [Xf, class] = simplecluster( X, cut ) | |
| % A simple clustering algorithm for point wise data | |
| % X :: Column Matrix of Points | |
| % cut :: Eucledean cutoff distance | |
| %% Distance Matrix | |
| D = pdist( X ); | |
| C1 = sparse( squareform( D <= cut ) + eye( size(X,1) ) ); | |
| %% Graph Power | |
| % Compute Graph Power until the number of nonzero elements doesn't change | |
| n1 = 0; | |
| C = C1; | |
| while n1 ~= nnz(C) | |
| n1 = nnz(C); | |
| C(:) = C1 * C'; | |
| end | |
| %% Cluster original points | |
| % Update clustered points | |
| [ ~,un,class] = unique( C, 'rows' ); | |
| Xf = zeros( numel( un ), size(X,2) ); | |
| for ii = 1 : size(X,2) | |
| Xf(:,ii) = accumarray( class, X(:,ii), [], @mean ); | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment