Why does ACCUMARRAY used with a custom function sometimes make unnecessary subfunction calls in MATLAB 7.6 (R2008a)?

2 views (last 30 days)
I have the defined the following function:
function A = testfun()
val = 101:105;
subs = [1 2 2 2 2;
1 1 3 1 3]';
A = accumarray(subs, val,[2 3], @(x) myfun(x));
function k = myfun(x)
disp(['new call to myfun with x = ' num2str(x')])
k={x};
end
end
When I run the above function, though I get the expected final result, A, it appears that more calls are made to the subfunction 'myfun' than are necessary:
new call to myfun with x = 101
new call to myfun with x = 102
new call to myfun with x = 101
new call to myfun with x = 104 102
new call to myfun with x = 105 103

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
This is an expected behavior of ACCUMARRAY in MATLAB 7.6 (R2008a).
In the documentation for ACCUMARRAY in MATLAB 7.6 (R2008a), it is mentioned that: "If the subscripts in subs are not sorted, fun should not depend on the order of the values in its input data."
In the example provided, the 'subs' matrix was:
subs = [1 1;
2 1;
2 3;
2 1;
2 3]
For a 2x3 output matrix, this corresponds to a linear indexing of:
IND = [1;
2;
6;
2;
6]
which is not sorted. Because sorting the output linear indices is so costly, ACCUMARRAY assumes that they are sorted, until it discovers otherwise, which is typically very early on.
In this case, it discovers otherwise when it gets to the last index. While gathering up the result for the 6th element of the output, it discovers that the next thing in the input is the 2nd element, and so it sorts the input and starts over. This is why it appears that extra calls than necessary are made to 'myfun'.
Observe that if the subscripts in the 'subs' matrix is sorted, then you will not see these "extra" calls. For example, if you run your code with:
subs = [1 2 2 2 2;
1 1 1 3 3]';
you will only see 3 calls to 'myfun':
new call to myfun with x = 101
new call to myfun with x = 102 103
new call to myfun with x = 104 105

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2008a

Community Treasure Hunt

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

Start Hunting!