File Exchange

image thumbnail


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


Updated 21 Feb 2020

View Version History

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 (2021). fastpower (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (8)

Michal Kvasnicka

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);

Michal Kvasnicka

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.

Michal Kvasnicka

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

Michal Kvasnicka

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.

Michal Kvasnicka

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

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

Community Treasure Hunt

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

Start Hunting!