Create a new vector by adding and subtracting each element of original vector.

Hello community,
I want to create a new vector by adding and subtracting each element of orginal vector. How can I do?
Example: A = [3 8 99 61]
What I want is: Output B = [2 3 4 7 8 9 98 99 100 60 61 62]

 Accepted Answer

B = reshape(A + [-1;0;+1],1,[]) % or
B = reshape(bsxfun(@plus,A,[-1;0;+1]),1,[]) % if < = 2016a

3 Comments

+1, The first line is clearly best
For releases prior ro r2016b, you can use a variant of the first line and avoid bsxfun() if you want.
B = reshape([A;A;A] + repmat([-1;0;1],1,size(A,2)),1,[]);
Thanks Adam :), at first sight the question seemed to be unclear actually.

Sign in to comment.

More Answers (0)

Categories

Asked:

on 6 Aug 2019

Edited:

on 6 Aug 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!