3

我刚刚阅读了 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

这对我来说是合乎逻辑的。但是,当我添加第二列时,为什么矩阵的数字B只是排列在“随机”(我猜它不是随机的,但对我来说似乎是随机的)位置?4x2subs

4

1 回答 1

3

摘自 accumarry 的 matlab 文档(注:以下引用来自 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
于 2017-02-15T09:03:35.480 回答