codeling
codeling

Reputation: 11369

Add fixed number of increasing values after each element in matrix

In Matlab, I have a list of numbers A (a vector), and would need to add after each of the entries a number n of additional entries with values being 1 higher than the previous.

So let's say I have A=[5 11 17], and n=1, I would need to make the resulting expression contain [5 6 11 12 17 18].

How can I do that? I've seen repmat and Tony's Trick, but they only replicate a vector and don't add anything to the values. Is there any expression I can apply on a Matrix that e.g. the row index is added to each element's value?

Please excuse me if this is really a simple task, I'm really new to Matlab and haven't wrapped my head around all the concepts there yet I think... glad for any pointers!

Upvotes: 2

Views: 202

Answers (2)

codeling
codeling

Reputation: 11369

Found a solution myself in the meantime. Not sure on whether it's efficient, but I thought I'd post it anyway:

result = repmat(A, n-1, 1)+repmat([1:n-1]-1,length(A),1).'
result = result(:)

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

Do the addition in two dimensions with bsxfun, and then reshape into a single row:

B = reshape(bsxfun(@plus, A, (0:n).'), 1, []); %'// A assumed to be a row vector

Example:

>> A = [5 11 17];
>> n = 2;
>> B = reshape(bsxfun(@plus, A, (0:n).'), 1, [])
B =
     5     6     7    11    12    13    17    18    19

Upvotes: 3

Related Questions