"Husam Aldahiyat" <numandina@gmail.com> wrote in message <h2n5b9$lo7$1@fred.mathworks.com>...
> Hello,
> I am learning MATLAB and when I read about the accumarray() function it looks good but I didn't understand how the examples worked.
>
> Could someone give me a nice small example (problem) and how accumarray solves it?

Any time that you wish to count the number of times
an element appears in a vector, accumarray is the
solution. Best is if the elements are small positive
integers.

x = ceil(10*rand(1,20))
x =
7 1 9 10 7 8 8 4 7 2 8 1 3 1 1 9 7 4 10 1

count = accumarray(x',1)
count =
5
1
1
2
0
0
4
3
2
2

If they are not small positive integers, then the third
argument of unique will provide the extra piece.

If you wish to see accumarray in action, it forms an
important part of my own consolidator utility on the
file exchange:

How is (7,8) within +/-1 of 3? If you mean to find the values in the second column which are +/-1 from each other, what do you expect when there are two such sets? Are we to return both sets? For example:

ACCUMARRAY may or may not be able to help here. The SUBS input determines how values in the VALS input are batched up when passed to your FUN, but FUN has no access to the SUBS values themselves. Thus, AUUMARRAY can easily return [1; 2; 3], but you will need to do something additional to get [1 1; 1 2; 1 3].

Ok, quite old thread, nevertheless I decided to post, because I'm quite happy right now, because I found out, accumarray() solves my problem perfectly:

Given you have a statistic "stat" in which results from different games are stored (one game per row). In the first column is a player id, in the second column a gain/loss for the player with a specific player id. The matrix "stat" contains infos about many games and one player can have multiple entries (one for every game he played). If you want to get the cumulated gain/loss for every player, you calculate: cumulated_score = accumarray(stat(:,1) , stat(:,2)) which returns a column vector. (Players with an id that is not contained in stat(:,1) will get a score of 0.) To get the cumulated score of player with id = 5 you enter cumulated_score(5).

Implementing this (in a fast manner) by yourself can be quite a PITA...