我编写了下面的代码来计算矩阵:
vec0=repmat(vec,1,9);
triw = (bsxfun(@times,vecO(1,:)',yc1)-bsxfun(@times,vecO(2,:)',xc1)).*(bsxfun(@times,vecO(2,:)',yc1)+bsxfun(@times,vecO(1,:)',xc1));vec是2乘900矩阵,xc1和yc1是8100×900.我在循环中使用这段代码。它很慢,所以我想提高它的性能。我该怎么做?
发布于 2017-09-20 17:32:40
通过将计算重组为对bsxfun的2个调用(而不是4个调用),我能够加快速度约30-40%:
triw = bsxfun(@times, prod(vec0).', yc1.^2-xc1.^2)-...
bsxfun(@times, diff(vec0.^2).', xc1.*yc1);注意,我还使用了阵列转置算子 .'而不是复共轭转置算子 '。第一种方法只是在不修改值的情况下对数组进行重组,而第二种方法在处理复杂数据时可以给出不同的结果。
下面是我用来比较这两种方法的代码:
% Random test data:
vec0 = rand(2, 8100);
xc1 = rand(8100, 900);
yc1 = rand(8100, 900);
% Define anonymous functions to test:
fcn1 = @(v, x, y) (bsxfun(@times, v(1, :).', y)-bsxfun(@times, v(2, :).', x)).*...
(bsxfun(@times, v(2, :).', y)+bsxfun(@times, v(1, :).', x));
fcn2 = @(v, x, y) bsxfun(@times, prod(v).', y.^2-x.^2)-...
bsxfun(@times, diff(v.^2).', x.*y);
% Test the mathematical accuracy:
triw1 = fcn1(vec0, xc1, yc1);
triw2 = fcn2(vec0, xc1, yc1);
max(abs(triw1(:)-triw2(:)))
ans =
4.440892098500626e-16
% Time the results:
t1 = timeit(@() fcn1(vec0, xc1, yc1))
t1 =
0.107775908242267 % seconds
t2 = timeit(@() fcn2(vec0, xc1, yc1))
t2 =
0.068403928901861 % seconds这两种结果的最大绝对差为双精度数的浮点相对精度阶,因此有效地没有差别。
https://stackoverflow.com/questions/46327432
复制相似问题