0

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
  • 27,562
  • 7
  • 28
  • 55
Nils
  • 409
  • 6
  • 16
  • Appending is [not a good idea](https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html) if you intend to do it continuously. Why do you want a loop? Use `b=repmat(a,1,3)` – Sardar Usama Jan 12 '18 at 11:27

2 Answers2

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]
Wolfie
  • 27,562
  • 7
  • 28
  • 55
1

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
Alex bGoode
  • 551
  • 4
  • 16
  • Whereas this is technically correct and the exact thing the OP asks for, it's a very bad idea in terms of memory and computing time management. – Adriaan Jan 12 '18 at 11:49
  • My assumption is, that this is more a question about basic syntax, than optimal memory and computing time management. – Alex bGoode Jan 12 '18 at 12:56
  • 1
    Thanks for your edit. Even if it is a basic syntax question it is best to not answer with bad habits or practises, as people then get used to doing things that way, messing up their later programming career since the bad habits are ingrained in their system. Besides, it creates more work for us on SO because they'll just come back complaining about slow code. Nonetheless, welcome to SO and keep up the good work! – Adriaan Jan 12 '18 at 13:51