Thursday, February 5, 2015

Choose bsxfun instead of repmat for faster code

I have recognized that using the repmat function might slow the code, it is significantly faster to use bsxfun, see the code snipplet below, bsxfun is about five times faster.

l = 1000
a = rand(l,2);
b = rand(1,2);
tic
for t = 1:1000
    c = bsxfun(@plus,a,b);
end
toc

tic
for t = 1:1000
    c = a+repmat(b,l,1);
end
toc

speed up your MATLAB code

A good tutorial to speed up MATLAB code is available here