0
Fertiggestellt

Overload element-wise operators

Jason Nicholson vor 7 Jahren aktualisiert von Pavel Holoborodko vor 6 Jahren 4

I think element-wise operators need overloaded. Here is an example of why. With double precision in MATLAB, this works. I think it should work for the mp data type too.


>> x = 1:10, y = (11:20)'

x =

     1     2     3     4     5     6     7     8     9    10

y =

    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

>> A = x.*y

A =

    11    22    33    44    55    66    77    88    99   110
    12    24    36    48    60    72    84    96   108   120
    13    26    39    52    65    78    91   104   117   130
    14    28    42    56    70    84    98   112   126   140
    15    30    45    60    75    90   105   120   135   150
    16    32    48    64    80    96   112   128   144   160
    17    34    51    68    85   102   119   136   153   170
    18    36    54    72    90   108   126   144   162   180
    19    38    57    76    95   114   133   152   171   190
    20    40    60    80   100   120   140   160   180   200

>> A = mp(x).*mp(y)
Error using  .*  (line 1644)
Matrix dimensions must agree




Wird überprüft

Dear Jason, 


Toolbox already overloads all element-wise operations. Moreover, the error message is perfectly valid, as arrays have incompatible dimensions - in fact,  all MATLABs up to 2016a return the same error message for this operation.

However a year ago (starting from R2016b), MATLAB developers added "implicit arithmetic expansion" to make this kind of operations valid [1].


IMHO the feature is questionable, as it could break old code (e.g. see [2]) and it makes new code incompatible with older MATLABs. 


This feature is not implemented in toolbox for the time being, please use classic MATLAB's techniques. 

For example, A = bsxfun(@times,x,y) does exactly this.


[1] https://blogs.mathworks.com/loren/2016/10/24/matlab-arithmetic-expands-in-r2016b/

[2] http://undocumentedmatlab.com/blog/afterthoughts-on-implicit-expansion 

What you are saying about change to implicit-expansion makes sense. I can accept that.


I did try bsxfun already. For some reason it seemed to be slower than just using a for loop. 


FOR LOOP Construction:

A = nan(size(u,1), size(exponent,1));

for i = 1:n
    A(:,i) = u(:,1).^(exponents(i,1));
end


bsxfun Construction:

A = bsxfun(@power, u(:,1), exponents(:,1)');


Majority of toolbox functions are implemented in C/C++ for the sake of speed. 


But "bsxfun" is one of the functions we implement using M-language. 

It has quite convoluted structure to cover many different use cases = extra overhead.


Manually coded special cases (like yours) are faster thanks to minimal overhead - all operations in this expression are  implemented directly in toolbox core in C/C++ with optimizations for CPU cache, etc.

Fertiggestellt

This functionality is available in newest toolbox version - 4.6.0.