0

I have a vector of the form:

A = [a1 a2 a3 a4 ...];

I want to create another vector like this:

B = [a1 a1 a1 a2 a2 a2 a3 a3 a3 a4 a4 a4 ...];

How can i do this?

user3482383
  • 295
  • 3
  • 11

1 Answers1

2

There are many ways to do this, for instance using the Kronecker tensor product like this:

B = kron(A,ones(1,3))

or combining reshape and repmat like this:

B = reshape(repmat(A,3,1),1,[])

if you're not sure if the vector is horizontal or vertical, you can use (:) and the transpose .' like this:

B = kron(A(:).', ones(1,3))
B = reshape(repmat(A(:).',3,1),1,[])

EDIT

You said the reshape version didn't work. Here are the results from my tests:

A = 1:4
B = reshape(repmat(A(:).',3,1),1,[])
B =
   1   1   1   2   2   2   3   3   3   4   4   4
A = (1:4)'
B = reshape(repmat(A(:).',3,1),1,[])
B =
   1   1   1   2   2   2   3   3   3   4   4   4

So, it works for both column and row vectors (at least for me).

Some more ways to do it:

%# vector-matrix product
reshape(ones(3,1)*A, 1,[])

%# reorganize simple concatenation
nA = 3*numel(A);    
B([1:3:nA 2:3:nA 3:3:nA]) = [A A A];
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
  • Among these many ways, which one is fastest? – user3482383 Jul 02 '14 at 10:01
  • I suggest you test this yourself using [`timeit`](http://www.mathworks.se/help/matlab/ref/timeit.html). It would be nice if you share the benchmark results here when you've tested it =) – Stewie Griffin Jul 02 '14 at 10:03
  • I tested it for a vector of random numbers with 1000 elements and repeating factor of 300, the time for kron function was t1=0.0373 and the time for reshape function was t2 = 0.0091. something about four times faster – user3482383 Jul 02 '14 at 10:10
  • Ok, this makes sense since `kron` involves arithmetic operations whereas repmat simply repeats the values. You can have a look at Luis' answer in the duplicate question. I haven't tested it, but it might be it's a bit faster. – Stewie Griffin Jul 02 '14 at 10:12
  • The reshape form does not working, it does not repeat each element, it repeats the whole vector!. In Luis answer what is the 1,2 and 3? how can i improve it for any vector? – user3482383 Jul 02 '14 at 10:34
  • @user3482383: Please see my update. And [1;2;3] is the vector he wants do duplicate. – Stewie Griffin Jul 02 '14 at 10:39