我需要确定每个唯一行向量在矩阵中出现的次数 我们假设我们有以下矩阵:
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}}在矩阵A中出现两次,而[1 0 1]
只出现一次?
我尝试了'count'和'sum'的各种应用,但是它们对矢量元素而不是矢量作为一个整体进行操作。非常感谢您对这个问题的指导。
答案 0 :(得分:3)
在Octave和MATLAB R2014a及更早版本中,您可以使用unique
和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或更高版本,请将使用折旧hist
的最后一行替换为histcounts
(建议使用)。
occ = histcounts(c);
或最好/最快,如 Luis Mendo 建议,您可以使用accumarray
。 Octave's documentation infact有一个与你的问题非常相似的例子。
occ = accumarray(c, 1);