Skip to content

Instantly share code, notes, and snippets.

@benfulcher
Created July 24, 2019 00:39
Show Gist options
  • Save benfulcher/f243bdc4ab80a7351f083f35bdd4db63 to your computer and use it in GitHub Desktop.
Save benfulcher/f243bdc4ab80a7351f083f35bdd4db63 to your computer and use it in GitHub Desktop.
Reorder rows of a matrix by hierarchical average linkage clustering on Euclidean distances
function [dataMatrixClustered,dataMatrixNorm] = clusterReorderRows(dataMatrix)
distanceMetric = 'Euclidean';
linkageMethod = 'average';
% Normalize columns:
dataMatrixNorm = zscore(dataMatrix);
% Pairwise distances:
R = pdist(dataMatrix,distanceMetric);
% Do hierarchical linkage:
links = linkage(R,linkageMethod);
f = figure('color','w');
set(gcf,'Visible','off'); % suppress figure output
[~,~,ord] = dendrogram(links,0);
close(f); % close the invisible figure used for the dendrogram
% Reorder rows:
dataMatrixClustered = dataMatrixNorm(ord,:);
% Plot:
figure('color','w');
subplot(1,2,1);
imagesc(dataMatrixNorm);
subplot(1,2,2);
imagesc(dataMatrixClustered);
end
@benfulcher
Copy link
Author

Note that the column normalization step is something you should think about for your application (also whether it makes sense to normalize along rows) [and also whether a normalization other than z-score is more suitable]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment