So, I've got X, a 300-by-1 vector and I'd like [1, X, X*X, X*X*X, ... , X*X*...*X], a 300-by-twenty matrix.
How should I do this?
X=[2;1]
[X,X.*X,X.*X.*X]
ans =
2 4 8
1 1 1
That works, but I can't face typing out the whole thing. Surely I don't have to write a for loop?
Use
bsxfun
for a neat solution, or go for Luis Mendo's extravaganza to save some time ;)gives:
If you want to minimize the number of operations:
Benchmarking: for
X
of size 300x1, maximum exponent 20. I measure time withtic
,toc
, averaging 1000 times. Results (averages):cumprod
(this answer): 8.0762e-005 secondsbsxfun
(answer by @thewaywewalk): 8.6170e-004 secondsThe element-wise power operator
.^
should do what you need:(assuming
x
is a column vector.)Use power. It raises something to the power of y, and repeats if y is a vector.
edit: power and .^ operator are equivalent.