How to generate the first twenty powers of x?

爷,独闯天下 提交于 2019-12-31 07:19:26

问题


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?


回答1:


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



回答2:


Use bsxfun for a neat solution, or go for Luis Mendo's extravaganza to save some time ;)

powers = 1:20;
x = 1:20;

result = bsxfun(@power,x(:),powers(:).');    

gives:

 1    1    1 ...
 8   16   32 ...
27   81  243 ...
64  256 1024 ...
... ...  ...



回答3:


The element-wise power operator .^ should do what you need:

x .^ (1:20)

(assuming x is a column vector.)




回答4:


Use power. It raises something to the power of y, and repeats if y is a vector.

power(x,1:300)

edit: power and .^ operator are equivalent.



来源:https://stackoverflow.com/questions/20314989/how-to-generate-the-first-twenty-powers-of-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!