How to generate the first twenty powers of x?

后端 未结 4 745
感情败类
感情败类 2021-01-28 18:42

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         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-28 19:13

    If you want to minimize the number of operations:

    cumprod(repmat(X(:),1,20),2) %// replace "20" by the maximum exponent you want
    

    Benchmarking: for X of size 300x1, maximum exponent 20. I measure time with tic, toc, averaging 1000 times. Results (averages):

    • Using cumprod (this answer): 8.0762e-005 seconds
    • Using bsxfun (answer by @thewaywewalk): 8.6170e-004 seconds

提交回复
热议问题