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 .
No, currently repmat
mostly is slow er than plain indexing, which works as follows:
Classis repmat
:
a = [ 1 2 3 ];
repmat(a,4,1)
>>
[1 2 3;
1 2 3;
1 2 3;
1 2 3];
indexing version of this:
a(ones(4,1),:);
which gives just the same result.
it really depends what sort of verctor you want. for example if you want aa specialized vector such as row of ones, then
tic
repmat([1],3,5)
toc
tic
ones(3,5)
toc
will tell you that using "ones" is about 3 times faster (at least on my machine). You can always use tic and toc to measure which method is faster. Lets try another one...
tic
repmat([1,2,3],1,2)
toc
tic
cat(2,[1,2,3],[1,2,3])
toc
now cat is 3 times faster again but it has its own obvious limitation. Hope this helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.