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?

1
  • Appending is not a good idea if you intend to do it continuously. Why do you want a loop? Use b=repmat(a,1,3) Commented Jan 12, 2018 at 11:27

2 Answers 2

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] 
Sign up to request clarification or add additional context in comments.

Comments

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 

3 Comments

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.
My assumption is, that this is more a question about basic syntax, than optimal memory and computing time management.
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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.