gpt4 book ai didi

algorithm - 如何在 MATLAB 中表示簇?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:41:58 25 4
gpt4 key购买 nike

假设我有以下数据集:

一个:

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 的数组(这将代表我的集群),其中包含 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的列代表加入到哪个簇中)。这就是我希望该行执行的操作,但出现上述错误。

有什么建议吗?

最佳答案

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com