How to add a repeating pattern to vector with diff

2019-09-03 10:31发布

问题:

Question

Suppose I have two vectors of arbitrary length. Lets call one pattern and the other series. Now I want to add my repeated pattern to my series in an automatic way.

Typically one can assume that pattern is shorter than series, but it would be nice if the alternate way also worked. In this case just the first few values of pattern should be used.

Example

pattern = 1:3;
series = 1:10;

Should give

 2     4     6     5     7     9     8    10    12    11

What have I found so far?

I have searched around but did not find an elegant way to achieve what I want.

  • The easiest solution I found uses padarray, however I do not have this available
  • My own solution,that I don't consider to be elegant, is using repmat to repeat the pattern a sufficient amount of times and then cutting of the end.

回答1:

You could use indexing instead of repmat:

result = series + pattern([mod(0:(numel(series) - 1), numel(pattern)) + 1]);


标签: matlab vector