假设我们有一个数组
A = zeros([1,10]);
我们有几个可能重复的索引:
indSeq = [1,1,2,3,4,4,4];
如何将 A(i)
增加索引序列中 i
的数量,即 A(1) = 2, A(2) = 1、A(3) = 1、A(4) = 3
?
代码A(indSeq) = A(indSeq)+1
不起作用。
我知道我可以使用下面的for循环来达到目标,但我想知道是否有什么办法可以避免for循环?我们可以假设 indSeq
已排序。
for循环解决方案:
for i=1:length(indSeq)
A(indSeq(i)) = A(indSeq(i))+1;
end;
最佳答案
您可以使用accumarray
对于这样一个基于标签的计数工作,就像这样 -
accumarray(indSeq(:),1)
基准测试
按照 other answer
中的建议,您还可以使用hist/histc
。让我们对这两个大数据量进行基准测试。我使用的基准测试代码有 -
%// Create huge random array filled with ints that are duplicated & sorted
maxn = 100000;
N = 10000000;
indSeq = sort(randi(maxn,1,N));
disp('--------------------- With HISTC')
tic,histc(indSeq,unique(indSeq));toc
disp('--------------------- With ACCUMARRAY')
tic,accumarray(indSeq(:),1);toc
运行时输出 -
--------------------- With HISTC
Elapsed time is 1.028165 seconds.
--------------------- With ACCUMARRAY
Elapsed time is 0.220202 seconds.
关于arrays - 如何在 MATLAB 中按特定值递增数组中的某些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34326016/