Repeat element of a vector n times without loop.
195 visualizzazioni (ultimi 30 giorni)
Say I have a column vector x=[a;b;c]. I want to repeat each element n times to make a long length(x)*n vector. For example, for n=3, the answer would be:
Can anyone think of an elegant way to do this without looping?
Più risposte (6)
Kevin Moerman il 29 Ago 2012
There is several others ways of doing it which in some cases are more efficient. Have a look at what the size of your vector is and compare the methods. Below I compare speeds and it appears that on my computer the third and fourth methods are mostly faster for large arrays.
a=zeros(n,numel(x)); b=a; c=a; d=a; %memory allocation
tic; a=repmat(x, n, 1); t1=toc; %Repmat method
tic; b=kron(x, ones(n,1)); t2=toc; %kron method
tic; c=x(ones(1,n),:); t3=toc; %indexing method
tic; d=ones(n,1)*x; t4=toc; %multiplication method