on the use of the accumarray function

1 次查看(过去 30 天)
Could someone please explain to me how the accumarray function works. For example:
val = 101:105;
subs = [1; 2; 4; 2; 4];
A = accumarray(subs,val)
A =
101
206
0
208
I cant understand why it performs the following calculations:
101 % A(1) = val(1) = 101
206 % A(2) = val(2)+val(4) = 102+104 = 206
0 % A(3) = 0
208 % A(4) = val(3)+val(5) = 103+105 = 208

采纳的回答

Sean de Wolski
Sean de Wolski 2012-9-10
编辑:Sean de Wolski 2012-9-10
Accumarray uses each sub as an index into the val vector. It then takes all values with this index and performs the operation on it (the dedault being sum)
Above:
  1. The index 1 is used onces corresponding to 101. 101 plus nothing else is 101.
  2. The index 2 is used twice corresponding to 102 and 104, these two numbers are summed.
  3. There is no occurence of index 3 so it is zero. (See note below)
  4. The index 4 corresponds to to 103 and 105, the rest is history...
Note
  • accumarray uses fillval to fill in elements who have no subs. You can set it using the 5th input to accumarray
-An accumarray fan

更多回答(1 个)

Jakob Hannibal
Jakob Hannibal 2014-11-23
When doing this:
vals=101:106';
subs= [1 1;2 2;3 2;1 1;2 2;4 1;]
A=accumarray(subs,vals)
A =
205 0
0 207
0 103
106 0
I don't get this? Shouldn't it be:
A=
205 311
207 310
104 0
106 0
  1 个评论
Sean de Wolski
Sean de Wolski 2014-11-24
No, each row of subs is an index combination. [3 1] is not one so A(3,1) should equal fill value. Consider it with just one rather than vals
subs= [1 1;2 2;3 2;1 1;2 2;4 1;]
A=accumarray(subs,1)
A =
2 0
0 2
0 1
1 0
Which is exactly what we see for subs: 2 sets of [1, 1], two sets of [2,2], one [3,2], and one [4,1]

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Dictionaries 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by