accumarray输出的解释

4

我刚刚阅读了accumarray的文档,但是无法理解第二个示例。示例如下:

val = 101:106';
subs = [1 1; 2 2; 3 2; 1 1; 2 2; 4 1]
subs =

     1     1
     2     2
     3     2
     1     1
     2     2
     4     1
A = accumarray(subs,val)
A =

   205     0
     0   207
     0   103
   106     0

如果我执行

B=accumarray(subs(:,1),val)
C=accumarray(subs(:,2),val)

然后我得到
B=

   205
   207
   103
   106

C =

   311
   310

这对我来说是合乎逻辑的。但是,当我给subs添加第二列时,为什么B的数字只是以“随机”(我猜它不是随机的,但对我来说看起来像随机的)的方式排列在一个4x2矩阵中?

1个回答

3

以下内容摘自matlab的accumarray文档(注:以下引用为R2012a版本的文档,与当前版本不完全匹配)

在subs中元素的位置决定了vals向量中所选取的值将被累加;subs中元素的值决定了输出中累加向量的位置。

因此,在您的示例中,“随机”顺序来自subs指定的位置。分解subs和最终结果的含义,我们可以得到以下内容:

val = 101:106';
subs = [1 1; 2 2; 3 2; 1 1; 2 2; 4 1]
subs =

     1     1    <-- take val(1) which is 101 and put it at position [1, 1] in the output
     2     2    <-- put 102 in position [2, 2]
     3     2    <-- put 103 in position [3, 2]
     1     1    <--- ...and so on
     2     2
     4     1
A = accumarray(subs,val)
A =

   205     0    <--- [1, 1] has value 101+104, [1, 2] has no value
     0   207    <--- [2, 1] has no value, [2, 2] has value 102+105
     0   103    <--- ...and so on
   106     0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接