Rash
Rash

Reputation: 4336

Expand column vector to left and right with certain offset to form 2D matrix - MATLAB

I have some vectors with random length like,

a = [ 20
      78
      90
      180];

b = [ 54
      102
      1020];

How can I produce metric with like n = 3 integers before and after each element like,

a1 = [17  18  19  20  21  22  23          b1 = [51   52   53   54   55   56   57
      75  76  77  78  79  80  81                99   100  101  102  103  104  105
      87  88  89  90  91  92  93                1017 1018 1019 1020 1021 1022 1023];
      177 178 179 180 181 182 183];

without any loops, Thanks in advance,

Upvotes: 2

Views: 111

Answers (1)

Divakar
Divakar

Reputation: 221514

Perfect setup for usage of bsxfun with @plus handle -

n = 3;
a1 = bsxfun(@plus,a,-n:n)
b1 = bsxfun(@plus,b,-n:n)

Here, -n:n acts as the summation (because of @plus) offset array.

Upvotes: 6

Related Questions