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:
ans=
a
a
a
b
b
b
c
c
c
Can anyone think of an elegant way to do this without looping?
I guess, you are right.repmat(1:3, 1, 2) = [1,2,3,1,2,3] but the OP wants[1,1,2,2,3,3]. Thenr = repmat(1:3, 2, 1); r = r(:) avoid theexpensive transposition of the matrix. Well, I admit that even reading this message will waste more time then millions of matrix transpositions will cost...
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.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
댓글 수: 1
이 댓글에 대한 바로 가기 링크
https://kr.mathworks.com/matlabcentral/answers/46898-repeat-element-of-a-vector-n-times-without-loop#comment_328477
이 댓글에 대한 바로 가기 링크
https://kr.mathworks.com/matlabcentral/answers/46898-repeat-element-of-a-vector-n-times-without-loop#comment_328477
댓글을 달려면 로그인하십시오.