Repeat element of a vector n times without loop.
571 ビュー (過去 30 日間)
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?
その他の回答 (6 件)
Kevin Moerman 2012 年 8 月 29 日
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