使用 Octave 计算数组中每个唯一向量的实例数的最有效方法是什么?
What is the most efficient way to count the number of instances of each unique vector in an array using Octave?
我需要确定每个唯一行向量在矩阵中出现的次数。
假设我们有以下矩阵:
A = [1 0 0,
1 0 1,
0 1 0,
1 0 0,
0 1 0]
通过使用 'unique' 函数,我们可以将唯一行向量标识为:
U = [1 0 0,
1 0 1,
0 1 0]
然后我们如何制表 [1 0 0] and [0 1 0]
在矩阵 A 中出现两次而 [1 0 1]
只出现一次?
我尝试了 'count' 和 'sum' 的各种应用,但它们对矢量元素而不是整个矢量进行操作。非常感谢您对这个问题的指导。
在 Octave 和 MATLAB R2014a 及更早版本中,您可以使用 unique
and hist
:
[U,~,c] = unique(A, 'rows'); %unique rows are given by 'a'
occ=hist(c); occ=occ(occ~=0); %number of occurrences of each row is given by 'occ'
如果您有 MATLAB R2014b 或更高版本,请替换使用 depreciated hist
with histcounts
(推荐)的最后一行。
occ = histcounts(c);
或所有的best/fastest,因为Luis Mendo suggested, you can use accumarray
. Octave's documentation事实上有一个与你的问题非常相似的例子。
occ = accumarray(c, 1);
我需要确定每个唯一行向量在矩阵中出现的次数。
假设我们有以下矩阵:
A = [1 0 0,
1 0 1,
0 1 0,
1 0 0,
0 1 0]
通过使用 'unique' 函数,我们可以将唯一行向量标识为:
U = [1 0 0,
1 0 1,
0 1 0]
然后我们如何制表 [1 0 0] and [0 1 0]
在矩阵 A 中出现两次而 [1 0 1]
只出现一次?
我尝试了 'count' 和 'sum' 的各种应用,但它们对矢量元素而不是整个矢量进行操作。非常感谢您对这个问题的指导。
在 Octave 和 MATLAB R2014a 及更早版本中,您可以使用 unique
and hist
:
[U,~,c] = unique(A, 'rows'); %unique rows are given by 'a'
occ=hist(c); occ=occ(occ~=0); %number of occurrences of each row is given by 'occ'
如果您有 MATLAB R2014b 或更高版本,请替换使用 depreciated hist
with histcounts
(推荐)的最后一行。
occ = histcounts(c);
或所有的best/fastest,因为Luis Mendo suggested, you can use accumarray
. Octave's documentation事实上有一个与你的问题非常相似的例子。
occ = accumarray(c, 1);