MATLAB: Counting the number of clusters

for loop

I have a list of pair of numbers for example (please see below). In this example, if we look at the first column, the number one (1) repeats 3 times with its pair 54, 106 and 143. Similarly the number 24 repeats two times with its corresponding pair 87 and 288. What i want to do is group all those that repeat to one cluster. In the example listed below there are 12 pairs. I want to group 1 with 54, 106, and 143 and call it as one cluster and do the same thing with any such repeating pairs (number 24 in this example). In the end I will have 12 – 2 = 10 clusters. I would appreciate if some one could help with a matlab code for this.
Thanks,
Sudharsan
[1 54
1 106
1 143
5 90
24 87
64 244
5 202
7 270
24 288
25 176
26 206
27 161]

Best Answer

% unique indices
idx = unique(data(:,1));
% clusters
cluster = arrayfun(@(idx)data(data(:,1) == idx,2),idx,'UniformOutput',false);
Then you can access your clusters with idx(i)and cluster{i}, where i = 1:length(idx)