gpt4 book ai didi

indexing - Octave:对索引元素求和

转载 作者:行者123 更新时间:2023-12-03 06:24:05 25 4
gpt4 key购买 nike

描述这一点的最简单方法是通过示例:

data = [1, 5, 3, 6, 10];
indices = [1, 2, 2, 2, 4];
result = zeroes(1, 5);

我希望 result(1)data 中索引为 1 的所有元素的总和,result( 2)data 中索引为 2 的所有元素的总和,依此类推。

这可以工作,但在应用于 64K 元素向量(将 5 更改为 65535)时速度非常慢:

result = result + arrayfun(@(x) sum(data(index==x)), 1:5);

我认为用 64K 元素创建 64K 向量会占用时间。有没有更快的方法来做到这一点?或者我需要找出一种完全不同的方法吗?

<小时/>
for i = [1:5]
idx = indices(i);
result(idx) = result(idx) + data(i);
endfor

但这是一种非常非 Octave 的方法。

最佳答案

鉴于 MATLAB 与 Octave 非常相似,我将提供在 MATLAB R2016b 上测试过的答案。看着documentation of Octave 4.2.1语法应该是相同的。

您需要做的就是:

result = accumarray(indices(:), data(:), [5 1]).'

这给出:

result =

1 14 0 10 0

由于 accumarray 的预期输入,因此需要重新整形为列向量 (arrayName(:))。将大小指定为 [5 1],然后转置结果以避免出现某些 MATLAB 错误。

accumarray 也在 MATLAB documentation 中进行了深入描述。

关于indexing - Octave:对索引元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42902397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com