【问题标题】:Get the counts of the unique elements and their count in matlab在matlab中获取唯一元素的计数及其计数
【发布时间】:2014-03-15 07:09:39
【问题描述】:

我有这个向量可以说

A = [1; 2; 3; 1; 2; 3; 1; 2; 3]

我怎样才能找到类似这样的独特元素及其数量?

1 = 3
2 = 3
3 = 3

我绝对可以遍历各个元素并使用一些幼稚的技术。我不想要那种解决方案,因为我的真实数据将在数百万范围内,所以我不能只遍历每个元素。

在matlab中最有效的方法是什么?

【问题讨论】:

标签: matlab linear-algebra sparse-matrix


【解决方案1】:

为了提高效率,这很难超越:

elements = unique(A);
counts = histc(A(:), elements);

【讨论】:

  • 不正确。 numel(unique(A)) 给了我 3。我想要 [3;3;3] 因为所有三个元素都重复了 3 次
  • @Notlikethat 这是一个挑战吗? :-)
【解决方案2】:

Notlikethat's answer 是要走的路。但是它的效率(计算时间)实际上可以提高:

sA = sort([A(:); inf]); %// sort A
ind = diff(sA)~=0; %// index of last element of each run of equal values
elements = sA(ind); %// unique elements
counts = diff([0; find(ind)]); %// lengths of runs

基准测试

clear all
A = randi(100,1e6,1); %// Example data. Large column vector

%// Notlikethat's answer
tic
elements = unique(A);
counts = histc(A(:), elements);
toc

clear elements counts

%// This answer
tic
sA = sort([A(:); inf]);
ind = diff(sA)~=0;
elements = sA(ind);
counts = diff([0; find(ind)]);
toc

Elapsed time is 0.175594 seconds.
Elapsed time is 0.076032 seconds.

【讨论】:

  • +1 始终相信在低级别可以提取更多性能!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-06
  • 1970-01-01
  • 2015-04-18
  • 1970-01-01
  • 2019-05-21
  • 2022-10-23
相关资源
最近更新 更多