0
Respost

Missing accumarray()

sedenka fa 7 anys updated by Pavel Holoborodko fa 7 anys 3

Hello,
I need to implement MATLAB built-in function accumarray(), which is not supported by the Advanpix toolbox (yet?). In order to use the same code for single/double/mp precision, I tried to overload accumarray by creating a new function in the mp class. Whenever I want to pass a vector of mp values to that function, it gets "messed up".


I have put this piece of code into the methods section of mp class:
function result = accumarray(subs, val, sz)
size(val)
val(1)
val(2)
keyboard
...
end


The code...
>> accumarray([1; 2; 2; 1; 1], mp([1;2;3;4;5]))
...returns...
ans =
5 1


ans =
1
2
3
4
5


Index exceeds matrix dimensions.


Error in mp/accumarray (line 5038)
val(2)


As you can see, the second argument has still its size (and numel) but all the content was somehow shrinked into the first element. Could you, please, help me with implementing of my own methods into the toolbox?


Best regards,
Vladimir

Under review

Hello Vladimir,


MATLAB has a bit strange rules for classes.

One of the "best" one is that element indexing doesn't work as expected inside methods of the class. So that when you call val(1) or val(2), A(1,:) or any other indexing operation - MATLAB calls default SUBSREF method which is suitable for double arrays but not for custom (like mp).


Instead you need to call overloaded SUBSREF, which is good for mp-objects (and which is provided in MP.M). There is special syntax for this:


subsref(val, substruct('()',{2}))    % equivalent to val(2) in normal world

You can find many examples of such calls in MP.M to learn from.


But, I would suggest you to write your own function in separate file, not as part of MP.M

Then you can use the usual syntax.

Dear Pavel,

thank you very much for the subsref()!

I thought I needed to add new method to the mp class in order to overload MATLAB's accumarray only when using mp. Do you think of overloading accumarray permanently and use something like...


function result = accumarray(subs, val, ...)

if isa(val, 'mp')

...perform fallback implementation

else

...use MATLAB's accumarray

end


Although I do not like putting my code into a code of someone else, I do hate "if"s even more :-). Anyway, the best solution would be an "official" implementation ;-). I'll leave it up to you.

Respost

The 'accumarray' has been added to new version of toolbox - 4.3.2.12172.

Please download and re-install toolbox on your computer.


Currently 'accumarray' is implemented in MATLAB language and thus can be slow for large arrays.

Other than that - it supports all the features, including sparse matrices, fill value, custom functions, etc.

Let me know if you encounter any issues.