help me understand accumarray
44 views (last 30 days)
Show older comments
hi i was reading on accumarray (https://www.mathworks.com/help/matlab/ref/accumarray.html) and I do not understand how matrix A was computed (attached picture) - how the second column of subs was manipulated and the zeros in A. Could someone explain how it is computed?
0 Comments
Accepted Answer
Daniel M
on 27 Oct 2019
Edited: Daniel M
on 27 Oct 2019
OK, so the subs matrix represent the rows and columns of the matrix A. (1, 1) represent the first row and first column. (3, 2) represents the 3rd row and 2nd column. If you don't get this, look at the document on ind2sub on this page.
Now the vals are associated with each row in subs (e.g. the first (1, 1) associated with 101, up to (4, 1) with 106). And the values get accumulated in the groups determined by the rows of subs.
Therefore, the two rows of (1, 1) have the values 101 and 104. This adds to 205, which is why A(1,1) = 205. (2, 2) are 102 and 105. Thus, A(2,2) = 207. (3,2) --> 103, A(3,2) = 103. (4,1) --> 106, A(4,1) = 106.
It's pretty clear if you look at the last image on the accumarray page.
0 Comments
More Answers (1)
Jordan
on 3 Mar 2025 at 21:51
For the simplest case shown in the first example as well as the image at the end of the function page. The acumarray function takes in two inputs for example vectors, ind and data. These must be equal lengths and thus the ind vector serves to index the data vector. The function then applies an input function, argument number 4 (fun), or by default applies the sum function to the data vector. The function is applied according to the unique indexes present in ind corresponding to values in data. Thus for the first example with inputs "data = [1 2 3 4 5 6]" and "ind = [1 3 4 2 4 1]" acumarray sums the '1' indexes 1+6, '2' indexes 4, '3' indexes 2, and '4' indexes 3+5. The result is thus "ans = [7 4 2 8]".
Very confusing documentation for this function in my opinion especially given the lack of detail in the "More About" section.
0 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!