获取数组A
并输出unique(A)
的最快方法是什么? A
]的唯一数组元素的集合以及在unique(A)
中将A
的第i个多项性排在第i位的多重数组
这是一个满口,所以这是一个例子。给定A=[1 1 3 1 4 5 3]
,我想:
unique(A)=[1 3 4 5]
mult = [3 2 1 1]
这可以通过繁琐的for循环来完成,但是想知道是否有办法利用MATLAB的数组特性。
答案 0 :(得分:7)
uA = unique(A);
mult = histc(A,uA);
可替换地:
uA = unique(A);
mult = sum(bsxfun(@eq, uA(:).', A(:)));
<强>基准强>
N = 100;
A = randi(N,1,2*N); %// size 1 x 2*N
%// Luis Mendo, first approach
tic
for iter = 1:1e3;
uA = unique(A);
mult = histc(A,uA);
end
toc
%// Luis Mendo, second approach
tic
for iter = 1:1e3;
uA = unique(A);
mult = sum(bsxfun(@eq, uA(:).', A(:)));
end
toc
%'// chappjc
tic
for iter = 1:1e3;
[uA,~,ic] = unique(A); % uA(ic) == A
mult= accumarray(ic.',1);
end
toc
N = 100
的结果:
Elapsed time is 0.096206 seconds.
Elapsed time is 0.235686 seconds.
Elapsed time is 0.154150 seconds.
N = 1000
的结果:
Elapsed time is 0.481456 seconds.
Elapsed time is 4.534572 seconds.
Elapsed time is 0.550606 seconds.
答案 1 :(得分:2)
[uA,~,ic] = unique(A); % uA(ic) == A
mult = accumarray(ic.',1);
accumarray
非常快。不幸的是,unique
有3个输出变慢。
迟到:
uA = unique(A);
mult = nonzeros(accumarray(A(:),1,[],@sum,0,true))
答案 2 :(得分:2)
S = sparse(A,1,1);
[uA,~,mult] = find(S);
我在an old Newsgroup thread找到了这个优雅的解决方案。
使用N = 1000
Elapsed time is 0.228704 seconds. % histc
Elapsed time is 1.838388 seconds. % bsxfun
Elapsed time is 0.128791 seconds. % sparse
进行测试:
accumarray
(在我的计算机上,Error: Maximum variable size allowed by the program is exceeded.
会产生data = [
{
"username": "Mike",
"code": "12345",
"city": "NYC"
}
]
)