on the use of the accumarray function

4 visualizaciones (últimos 30 días)
Richard
Richard el 10 de Sept. de 2012
Comentada: Sean de Wolski el 24 de Nov. de 2014
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

Respuesta aceptada

Sean de Wolski
Sean de Wolski el 10 de Sept. de 2012
Editada: Sean de Wolski el 10 de Sept. de 2012
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

Más respuestas (1)

Jakob Hannibal
Jakob Hannibal el 23 de Nov. de 2014
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 comentario
Sean de Wolski
Sean de Wolski el 24 de Nov. de 2014
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]

Iniciar sesión para comentar.

Categorías

Más información sobre Dictionaries en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by