向量化属于一个组的求和值 [英] Vectorize summing values that belong to a group

查看:78
本文介绍了向量化属于一个组的求和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对经过不同索引映射的循环进行矢量化处理?例如:

Is it possible to vectorize a loop that goes through different index mappings? For example:

a = zeros(1, 5);
m = [4 3 5; 5 1 3];
f = [1 2 3; 4 5 6];

for ii = 1:size(m,1)
    a(m(ii,:)) = a(m(ii,:)) + f(ii,:);
end

给出输出:

a = [5 0 2+6 1 3+4] = [5 0 8 1 7]

可以在没有for循环的情况下完成此操作吗?

Can this be done without the for loop?

推荐答案

这是 accumarray . accumarray通过提供一组键和与每个键关联的一组值来工作. accumarray对属于同一键的所有值进行分组,并对所有值执行某些操作.默认行为是将属于同一键的所有值加在一起,这就是您要执行的操作.

This is a classic case of accumarray. accumarray works by providing a set of keys and a set of values associated with each key. accumarray groups all values that belong to the same key and does something to all of the values. The default behaviour is to sum all of the values that belong to the same key together, which is what you're after.

在您的情况下,m是键,而f是您要累加的属于同一键的值.因此:

In your case, m are the keys and f are the values you want to add up that belong to the same key. Therefore:

>> a = accumarray(m(:), f(:))

a =

     5
     0
     8
     1
     7

通常,您可能缺少一些密钥.因此,您可以选择指定输出数组的输出尺寸,该尺寸应为在m中看到的 maximum 键值:

In general, you may have keys that are missing. Therefore, you may opt to specify the output dimensions of the output array where it should be the maximum key value seen in m:

a = accumarray(m(:), f(:), [max(f(:)), 1]);

这当然是假设f严格由正值组成.

This is of course assuming that f consists of strictly positive values.

通常,如果f中有浮点数,则开箱即用的accumarray将不起作用,因为假定键严格是正数和整数.但是,一个常见的技巧是为f的每个值分配唯一的ID,并将其用作accumarray的输入. unique 的第三项输出应该为您完成.您还需要unique的第一个输出,以帮助您确定哪个总和属于哪个键:

In general, if you have floating point numbers in f, then accumarray out of the box won't work because the keys are assumed to be strictly positive and integer. However, a common trick is to assign a unique ID to each value of f and use this as the input into accumarray. The third output of unique should do this for you. You'll also need the first output of unique to help you figure out which sum belongs to what key:

[msorted,~,id] = unique(m);
a = accumarray(id, f(:));
out = [msorted a];

out将包含2列矩阵,其中每一行在m中为您提供一个唯一值,并为在m中共享同一键的所有值提供关联的总和.

out will contain a 2 column matrix where each row gives you a unique value in m and the associated sum for all values that shared the same key in m.

这篇关于向量化属于一个组的求和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆