Columnwise power operation in matrix

4 views (last 30 days)
Hi everyone (first post here)!
Say I have a vector x = [1;2;3].
I would like to construct a matrix X, where every column is the vector x raised to the power of the column number:
1 1 1
X = 2 4 8
3 9 27
With a for-loop, this is easily done:
for i=1:3
X(:,i) = x.^i;
end
But could this be done with vector operation instead of using a for loop?

Accepted Answer

Walter Roberson
Walter Roberson on 25 Mar 2013
bsxfun( @power, x, 1:3 )
  2 Comments
Alexander
Alexander on 25 Mar 2013
Wow, thank's very much, I appreciate it!
Matt J
Matt J on 25 Mar 2013
But don't use this for fitting polynomials! Use POLYFIT instead.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!