What is the most efficient way for repeating a vector?
I'm currently under the impression that repmat
is superior to any other methods? Or am I horribly wrong with this mindset?
Would it be possible to produce the exact same result as repmat
does, using a different technique? Perhaps ordinary matrix multiplication?
I would like to express my greatest gratitude for all your interest and supportive answers!
AER
The bottom line, bsxfun
is faster than the two you asked for if the start vector is long or the # of repeats is big enough (see below), otherwise matrix multiplication is more efficient. Between the two you've asked it looks like matrix multiplication+reshape wins in efficiency by a factor of ~3 over repmat
. I've used timeit
the following way, I've created a random vector of 1e5 elements and checked how long it takes to create 100 repeats of it:
v=rand(1e5,1);
f1=@()repmat(v,[100,1])
f2=@() reshape(v*ones(1,100),[],1);
timeit(f1)
ans =
0.1675
timeit(f2)
ans =
0.0516
however bsxfun
is even faster:
f3=@() reshape(bsxfun(@times,v,ones(1,100)),[],1)
timeit(f3)
ans =
0.0374
Here's a more careful study of this observation:
Given a vector is 1000 elements long, repeating it 10 to 1e5 times yield the following performance times:
For smaller # of repeats there is little difference between bsxfun
and matrix multiplication but as the # of repeats passes ~1e3, bsxfun
wins clearly.
However, taking a mere 10 elements long vector with the same range of repeats, shows that matrix multiplication is more efficient. bsxfun
starts to be better only after 10^5 repeats, but even then it is only ~5% faster (not shown) :
so it depends really what you're after. Further discussion is found in Loren on the Art of MATLAB blog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With