【发布时间】:2018-03-14 08:32:58
【问题描述】:
在我的代码的某些部分,我使用 repmat 来表示一个非常大的向量
vecO=repmat(vec,1,9);
fi = repmat(vecO',1,400)-A;
vec 是 1 x 400 矩阵,“A”是 3600 x 400 矩阵。我认为应该有一种比使用 repmat 更省时的方法,但我不知道方法是什么。有人有什么主意吗?
【问题讨论】:
标签: matlab optimization
在我的代码的某些部分,我使用 repmat 来表示一个非常大的向量
vecO=repmat(vec,1,9);
fi = repmat(vecO',1,400)-A;
vec 是 1 x 400 矩阵,“A”是 3600 x 400 矩阵。我认为应该有一种比使用 repmat 更省时的方法,但我不知道方法是什么。有人有什么主意吗?
【问题讨论】:
标签: matlab optimization
这是一个可以使用的模板测试,包括mikkola's answer:
vec = rand(1,400);
A = rand(3600,400);
n_expts = 1000;
format long
disp(version);
% Warm up
for ii = 1:n_expts
vec0 = repmat(vec,1,9);
res1 = repmat(vec0',1,400)-A;
res3 = bsxfun(@minus, vec0.', A);
end
tic
for ii = 1:n_expts
vec0 = repmat(vec, 1, 9);
res1 = repmat(vec0.', 1, 400) - A;
end
fprintf('Time taken with 2 repmats: ')
disp(toc/n_expts)
tic
for ii = 1:n_expts
res2 = repmat(vec.', 9, 400) - A;
end
fprintf('Time taken with 1 repmat and transpose: ')
disp(toc/n_expts)
tic
for ii = 1:n_expts
res3 = bsxfun(@minus, vec0.', A);
end
fprintf('Time taken with bsxfun: ')
disp(toc/n_expts)
% Check that all the fi are the same
dres1 = max(max(abs(res1 - res2)));
dres2 = max(max(abs(res1 - res3)));
tol = eps;
if (dres1 > eps) | (dres2 > eps)
fprintf('Difference in output matrices');
end
有结果
8.3.0.532 (R2014a)
Time taken with 2 repmats: 0.004027661867427
Time taken with 1 repmat and transpose: 0.004034170491803
Time taken with bsxfun: 0.003970521454027
【讨论】:
repmat 比一次调用二维展开要快。
repmat(vec, 400, 9)' - A,但花了大约 3 倍的时间。