【问题标题】:How to represent clusters in MATLAB?如何在 MATLAB 中表示集群?
【发布时间】:2016-04-05 19:11:54
【问题描述】:

假设我有以下数据集:

A

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

B

6 3 
1 9
0 7

我要做的是对于B中的每一行,找到最小值并获取它出现的列索引。例如,对于B中的第1行,最小值是3 来自 2 列。因此将 A 中的第 1 行添加到 Cluster 2

B 中的第 2 行,最小值为 1,来自 1 列。因此将 A 中的第 2 行添加到 Cluster 1。等等……

现在我想创建一个名为 C 的数组(这将代表我的集群),其中包含 2 个项目。第 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的列代表将其添加到哪个集群)。这就是我希望该行执行的操作,但出现上述错误。

有什么建议吗?

【问题讨论】:

  • 使C 成为一个元胞数组。然后它可以有大小不等的元素。

标签: algorithm matlab k-means


【解决方案1】:

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

[~, 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

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2020-04-30
    • 1970-01-01
    • 2017-07-27
    • 2012-01-15
    相关资源
    最近更新 更多