Repeat element of a vector n times without loop.
显示 更早的评论
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?
Thanks,
Justin
1 个评论
John
2015-12-9
U can use repmat it not exactly elegant but it will do the job
x=[a;b;c]; n=3;
newx = [repmat(x(1),n,1);repmat(x(2),n,1);repmat(x(3),n,1)]
采纳的回答
更多回答(6 个)
jack
2015-11-23
19 个投票
I would use
repelem(X,3,1)
3 个评论
Yuzhen Lu
2021-2-18
Very neat answer!
Arif Billah
2023-8-1
This should be chosen as the best 'correct' answer, thanks!
Walter Roberson
2012-8-28
kron(x, ones(n,1))
4 个评论
Vinay Chakravarthi
2015-1-20
Thx man.......
Phat Nguyen
2017-4-7
Very nice man
Abdelrahman Abdeltawab
2018-12-13
编辑:Abdelrahman Abdeltawab
2018-12-13
Dear Walter Roberson,
why you did not use outer product and you chosen kronecker ( just curious ) because the guy's question was having vectors ?
Walter Roberson
2018-12-14
The * matrix multiplication operator cannot by itself repeat elements. You would need something like
(x.' * repmat(eye(length(x)), 1, n)).'
if you wanted to use the * operator to duplicate elements -- forcing you to call upon repmat() to duplicate elements.
Using the kronecker is a known idiom for duplicating data. It can be used for non-vectors too.
>> kron([1 2;3 4], ones(3,1))
ans =
1 2
1 2
1 2
3 4
3 4
3 4
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.
n=100000; x=1:3;
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
Kevin
2 个评论
Vinay Chakravarthi
2015-1-20
Thx Man..
format long g
n=100000; x=1:3;
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
Jianshe Feng
2016-10-3
0 个投票
y = repmat(x,1,3); y = transpose(y); y = y(:);
Jianshe Feng
2016-10-3
0 个投票
ind = [1;1;1;2;2;2;3;3;3]; x(ind)
1 个评论
Walter Roberson
2017-4-7
Ah, but how do you construct the ind vector for general length n repetitions ?
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!