user449351
user449351

Reputation: 21

Populate a vector in Matlab using a smaller vector

I need to populate a vector with elements of another, smaller vector. So say the vector I need to populate is of length ten and is currently all zeros, i.e.

vector = [0,0,0,0,0,0,0,0,0,0]

Now suppose I have already define a vector

p = [1, 2, 3, 4, 5]

How could I populate "vector" with the array "p" so that the result is [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]? Bear in mind, I want the other positions in "vector" to remain unchanged. I have already tried using repmat(p, length(p)) but that ends up giving me something of the form [1,2,3,4,5,1,2,3,4,5]. Thanks!

Upvotes: 2

Views: 101

Answers (1)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27271

Try a combination of vector slicing and concatenation:

vector = cat(1, p, vector(5:))

This is faster:

vector(1:5) = p

More generally,

vector(1:numel(p)) = p

Upvotes: 5

Related Questions