File Exchange

image thumbnail

fastpower

version 1.0.2 (1.46 KB) by Natan
faster x.^n integer power of a vector

1 Download

Updated 21 Feb 2020

View License

Make use of the fact that for vectors of length greater than >~100 elements it is more efficient to use multiple x.^2 than x.^n, where n is an integer n>=3 until and n~250 (test on your system). The performance can be x10-x100 better depends on the vector length and power.

Cite As

Natan (2020). fastpower (https://www.mathworks.com/matlabcentral/fileexchange/74292-fastpower), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (8)

Finally I propose much simpler function with very similar performance:

function A = fastpower_new(x,n)
% check if N is integer
if n ~= fix(n)
error('N is not integer');
end
% Transform power to multiplication
fh= str2func(['@(x) ' repmat('x.*',[1, n-1]) 'x'] );
% evaluation power
A = fh(x);
end

Obviously the power operator A.^B is intended to solve mainly case for floating point B. The integer B is simply possible transform to multiplication, which generally much faster.

This behaviour of ".^" is not normal ...

I mean problem could be on Matlab site...

Natan

I'd love to learn about bugs or "Bad implementations", care to give an example? I tested this code and for n>=3 and ~>100 elements vectors it is a lot faster. The difference between this and x.^n is just the floating point accuracy of the class of the information of the vector, i.e. ~1e-16 for double.

Looks like a bug or bad implementation of
". ^" operator.

Updates

1.0.2

edited the description for the upper limit of n for which the code is faster,

1.0.1

typo correction, example show both performance and accuracy of code

MATLAB Release Compatibility
Created with R2019b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories