Home Append a vector by his own multiple times within a loop

# Append a vector by his own multiple times within a loop

Nils Kohlmey
1#
Nils Kohlmey Published in 2018-01-12 11:15:02Z
 This question already has an answer here: Octave / Matlab: Extend a vector making it repeat itself? 2 answers I think it should be very easy, but i donĀ“t know how to a append a vector by his own within a loop. For example: a = [1 2 3]  I would like to have: b = [1 2 3 1 2 3 1 2 3]  So, there must be an empty array where i append the a vector 3 times via a loop?
Wolfie
2#
 The answer is to use the built-in function repmat a = [1 2 3] % Repeat 1x in the rows dimension, 3x in the columns dimension b = repmat( a, 1, 3 ); % >> b = [1 2 3 1 2 3 1 2 3] 
 To append two vectors use the [a, b] notation. For your example: a = [1 2 3]; b = []; for i=1:3 b = [b, a]; end  Edit in response to the comment about memory allocation time: Consider pre-allocating the whole array before your loop. a = [1 2 3]; b= zeros(1, size(a,2)*3); s_a = size(a,2); for i=1:3 b(((i-1)*s_a + 1):i*s_a) = a; end