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.
Natan (2021). fastpower (https://www.mathworks.com/matlabcentral/fileexchange/74292-fastpower), MATLAB Central File Exchange. Retrieved .
I you want create nearly optimal algorithm you should read:
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');
% Transform power to multiplication
fh= str2func(['@(x) ' repmat('x.*',[1, n-1]) 'x'] );
% evaluation power
A = fh(x);
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.
The topic has been discussed many times:
This behaviour of ".^" is not normal ...
I mean problem could be on Matlab site...
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.
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!