Joh*_*den 0 matlab vectorization octave
所以,我有X,一个300乘1的矢量,我想要[1,X,X*X,X*X*X,......,X*X*...*X],一个300乘20的矩阵.
我该怎么做?
X=[2;1]
[X,X.*X,X.*X.*X]
ans =
2 4 8
1 1 1
Run Code Online (Sandbox Code Playgroud)
这是有效的,但我无法打字输出整个事情.当然我不必写一个for循环?
使用bsxfun一个简洁的解决方案,或去Luis Mendo的盛会节省一些时间;)
powers = 1:20;
x = 1:20;
result = bsxfun(@power,x(:),powers(:).');
Run Code Online (Sandbox Code Playgroud)
得到:
1 1 1 ...
8 16 32 ...
27 81 243 ...
64 256 1024 ...
... ... ...
Run Code Online (Sandbox Code Playgroud)
如果要最小化操作次数:
cumprod(repmat(X(:),1,20),2) %// replace "20" by the maximum exponent you want
Run Code Online (Sandbox Code Playgroud)
基准测试:X尺寸为300x1,最大指数为20.我用tic,测量时间toc,平均1000次.结果(平均值):
cumprod(此答案):8.0762e-005秒bsxfun(@thewaywewalk回答):8.6170e-004秒