有时最直接的方法是最快的!
c = zeros(size(a, 1), size(a, 2) * size(b, 2));
ic = 1;
for ib = 1:size(b, 2)
for ia = 1:size(a, 2)
c(:, ic) = a(:, ia) + b(:, ib);
ic = ic + 1;
end
end
例子
a = randn(10, 20);
b = randn(10, 30);
% # Originally proposed method
tic
c1 = bsxfun(@plus, a, permute(b, [1 3 2]));
c1 = reshape(c1, [size(a, 1), size(a, 2) * size(b, 2)]);
toc
% # Method suggested by gevang
tic
[pB, pA] = meshgrid(1:size(b, 2), 1:size(a, 2));
c2 = a(:, pA(:)) + b(:, pB(:));
toc
% # Direct approach
tic
c3 = zeros(size(a, 1), size(a, 2) * size(b, 2));
ic = 1;
for ib = 1:size(b, 2)
for ia = 1:size(a, 2)
c3(:, ic) = a(:, ia) + b(:, ib);
ic = ic + 1;
end
end
toc
结果是:
Elapsed time is 0.005850 seconds.
Elapsed time is 0.009442 seconds.
Elapsed time is 0.000328 seconds.
如您所见,for
在这种情况下,双循环几乎快 20 倍......