如何产生x的前20个幂? [英] How to generate the first twenty powers of x?
本文介绍了如何产生x的前20个幂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,我有X,一个300×1的向量,我想要[1,X,X * X,X * X * X,...,X * X * ... * X],一个300 x 20的矩阵.
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.
我应该怎么做?
X=[2;1]
[X,X.*X,X.*X.*X]
ans =
2 4 8
1 1 1
那行得通,但是我不能面对整个事情.当然我不必编写for循环了吗?
That works, but I can't face typing out the whole thing. Surely I don't have to write a for loop?
推荐答案
如果您要最小化操作次数:
cumprod(repmat(X(:),1,20),2) %// replace "20" by the maximum exponent you want
基准化:对于大小为300x1的X
,最大指数为20.我用tic
,toc
来测量时间,平均为1000次.结果(平均值):
Benchmarking: for X
of size 300x1, maximum exponent 20. I measure time with tic
, toc
, averaging 1000 times. Results (averages):
- 使用
cumprod
(此答案):8.0762e-005秒 - 使用
bsxfun
(@ thewaywewalk的回答):8.6170e-004秒
- Using
cumprod
(this answer): 8.0762e-005 seconds - Using
bsxfun
(answer by @thewaywewalk): 8.6170e-004 seconds
这篇关于如何产生x的前20个幂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文