How to find 6 clusters

3 ビュー (過去 30 日間)
Tim Navr
Tim Navr 2016 年 4 月 6 日
回答済み: Andrei Bobrov 2016 年 4 月 6 日
Hi. Thanks for looking
I have a 6000x1 matrix. The values are split into 6 clusters, each cluster is identified by a number (the number is not known). In between the clusters there are many 0 values. What would be the best way to split them into 6 different matrices, eg
A= [0 0 1 1 1 0 0 0 200 200 200 0 0 300 300 300 300 0 0 0 0 0 0 425 425 425 425 425]'
I need to put the row values of all ones into a matrix, then all 200's into another and so on
Thank you for your help

採用された回答

Andrei Bobrov
Andrei Bobrov 2016 年 4 月 6 日
A = A(:);
l = A > 0;
z = cumsum([l(1);diff(l)==1]);
out = accumarray(z(l),A(l),[],@(x){x});

その他の回答 (1 件)

Ced
Ced 2016 年 4 月 6 日
編集済み: Ced 2016 年 4 月 6 日
And each cluster is a repetition of the exact same number? Can the same number appear twice?
If not, you could do something like
A= [0 0 1 1 1 0 0 0 200 200 200 0 0 300 300 300 300 ...
0 0 0 0 0 0 425 425 425 425 425]';
A(A==0) = []; % remove zeros
clusters = unique(A);
N_clusters = length(clusters); % how many numbers
N_occurrences = arrayfun(@(x)sum(A==x),clusters); % how big are the clusters
new_mat = cell(N_clusters);
for i = 1:N_clusters
new_mat{i} = clusters(i)*ones(1,N_occurrences(i)); % one row for each cluster
end
To be fair, just saving N_clusters and N_occurrences already contains all the information, there is not really any need to create new_mat in general.
  1 件のコメント
Tim Navr
Tim Navr 2016 年 4 月 6 日
編集済み: Tim Navr 2016 年 4 月 6 日
I need to keep the original row number of each repetitive number. Each cluster is the repetition of the same number (but I don't know the number). And the clusters can be variable in length and I don't know the number of members in the clusters. Also, there can only be 6 clusters. Thank you

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by