最も直接的なアプローチが最も速い場合もあります。
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 倍高速です...