假设我有以下数据集:
答:

1   8   9   12
2   1   0   35
7   0   0   23

B:
6 3
1 9
0 7

我要做的是对b中的每一行,找到最小的值,然后得到它出现在其中的列索引。例如,对于B中的第1行,最小值为3,该值来自列2。因此,将第1行从a添加到Cluster 2
对于B中的第2行,最小值为1,该值来自列1。因此,将第2行从A添加到Cluster 1等等…
现在我想创建一个名为c的数组(这将表示我的集群),其中有两个项。项1包含A中应在Cluster 1中的所有行的矩阵,项2包含A中应在Cluster 2中的所有行的矩阵这就是我有问题的地方。这是我目前的尝试:
function clusterSet = buildClusters(A, B)
clusterSet = zeros(size(B, 2)); % Number of clusters = number of columns in B
for i = 1:size(A, 1)
    [value, index] = min(B(i,:)); % Get the minimum value of B in row i, and its index (column number)
    clusterSet(index) = A(i,:); % Add row i from A to its corresponding cluster's matrix.
end
end

最后一行出现以下错误(注意:这不是显式地引用我的数据集“A”和“B”,而是泛指A和B):
In an assignment  A(I) = B, the number of elements in B and I must
be the same.

如果行1中b的最小值来自列2,则a中的行1应添加到矩阵Cluster 2(b的行对应于要添加到群集的a的哪一行,b的列代表要添加到哪个群集)。这就是我想要那条线做的,但是我得到了上面的错误。
有什么建议吗?

最佳答案

这里有一种没有循环的方法:

[~, cluster] = min(B,[],2); %// get cluster index of each row
[clusterSort, indSort] = sort(cluster); %// sort cluster indices
sz = accumarray(clusterSort,1); %// size of each cluster
C = mat2cell(A(indSort,:), sz); %// split A into cell array based on clusters

关于algorithm - 如何在MATLAB中表示集群?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34552766/

10-13 00:09