Say i have two martrices:
A=50;
B=50;
C=1000;
X = rand(A,B);
Y = rand(A,B,C);
I want to subtract X
from each slice C
of Y
. This is a fairly common problem and i have found three alternative solutions:
% Approach 1: for-loop
tic
Z1 = zeros(size(Y));
for i=1:C
Z1(:,:,i) = Y(:,:,i) - X;
end
toc
% Approach 2: repmat
tic
Z2 = Y - repmat(X,[1 1 C]);
toc
% Approach 3: bsxfun
tic
Z3=bsxfun(@minus,Y,X);
toc
I'm building a program which frequently (i.e., many thousands of times) solves problems like this, so i'm looking for the most efficient solution. Here is a common pattern of results:
Elapsed time is 0.013527 seconds.
Elapsed time is 0.004080 seconds.
Elapsed time is 0.006310 seconds.
The loop is clearly slower, and bsxfun is a little slower than repmat. I find the same pattern when i element-wise multiply (rather than subtract) X
against slices of Y
, though repmat and bsxfun are a little closer in multiplication.
Increasing the size of the data...
A=500;
B=500;
C=1000;
Elapsed time is 2.049753 seconds.
Elapsed time is 0.570809 seconds.
Elapsed time is 1.016121 seconds.
Here, repmat is the clear winner. I'm wondering if anyone in the SO community has a cool trick up their sleeves to speed this operation up at all.