3

Starting with A = [3;4;5], I want to duplicate it six times to get A =[3;3;3;3;3;3;4;4;4;4;4;4;5;5;5;5;5;5].

I can think of some brute force ways to do it, but looking for something optimized since this will be run through a loop many times.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
user1956609
  • 2,132
  • 5
  • 27
  • 43
  • possible duplicate of [A similar function to R's rep in Matlab](http://stackoverflow.com/questions/14615305/a-similar-function-to-rs-rep-in-matlab) – Dan Jan 14 '14 at 06:23

3 Answers3

4

How about using kron? It's very suited for this purpose.

kron(A,ones(6,1))
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
1

Yet another possibility, which involves no arithmetical operations:

reshape(repmat(A,1,6).',[],1);

However, if you really need speed, and if the A vector size is the same in all iterations of the loop, it's best to precompute (outside the loop) an indexing vector like this

ind = reshape(repmat([1;2;3],1,6).',[],1);

and then within the loop you only need to do

A(ind)
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0
A = [3;4;5];
duplicate_factor = 6;
A = reshape((A*(ones(duplicate_factor,1))')', [], 1)
Franck Dernoncourt
  • 77,520
  • 72
  • 342
  • 501