arrays - 如何在 MATLAB 中按特定值递增数组中的某些元素

标签 arrays performance matlab vectorization run-length-encoding

假设我们有一个数组

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/

相关文章:

javascript - 将js文件中的数组Fatch到php中,然后编码成json

java - 如何使用 api 获取数据,我正在使用 api.weathermap.org ;但我只能获取一些数据

c - 如何在c中没有for循环的情况下将用户输入存储在数组中

javascript - ctx.lines() 在 Mac 上最多需要 8.7 秒,但在任何其他浏览器中不到 1 毫秒

MATLAB 错误 : Subscript indices must either be real positive integers or logicals

python - Numpy:在另一个 numpy 数组中创建一批 numpy 数组( reshape )

performance - 非时间负载和硬件预取器,它们可以一起工作吗?

javascript - 使用 Javascript 创建 HTML...从页面复制或存储在变量中?

MATLAB:对变量更改执行回调?

matlab - 访问图中的图以在 MATLAB 中添加新图