6
$\begingroup$

Let's say that I have this list

a={{-2, 1}, {-1, 2}, {0, 1}, {1, 0}, {2, 0}}

and I'd like to change the value of the elements in the column to obtain something like this

b={{-2, 0}, {-1, 0}, {0, 1}, {1, 2}, {2, 1}}

so, you can see that it's like I'm shifting the values in the column two positions.

and then I'd like to sum the elements in the column to obtain

c={{-2, 1}, {-1, 2}, {0, 2}, {1, 2}, {2, 1}}
$\endgroup$
2
  • $\begingroup$ I'm shifting the values in the column two positions btw, it is actually a shift by 3 not 2. $\endgroup$
    – Nasser
    May 27 '20 at 7:02
  • 4
    $\begingroup$ @Nasser It's three if you rotate to the left but two if you rotate to the right. $\endgroup$
    – C. E.
    May 27 '20 at 7:42
7
$\begingroup$
a = {{-2, 1}, {-1, 2}, {0, 1}, {1, 0}, {2, 0}}
before = a[[All, 2]];
a[[All, 2]] = RotateLeft[a[[All, 2]], 3];
a[[All, 2]] = a[[All, 2]] + before;

Now a is your c

Step-By-Step

 (a = {{-2, 1}, {-1, 2}, {0, 1}, {1, 0}, {2, 0}}) // MatrixForm

Mathematica graphics

before = a[[All, 2]];
a[[All, 2]] = RotateLeft[a[[All, 2]], 3];
(b = a) // MatrixForm

Mathematica graphics

b[[All, 2]] = b[[All, 2]] + before;
(c = b) // MatrixForm

Mathematica graphics

$\endgroup$
6
$\begingroup$
SubsetMap[RotateRight[#,2]&, a, {All,2}]

{{-2, 0}, {-1, 0}, {0, 1}, {1, 2}, {2, 1}}

%==b

True

For Part 2, see this recent question

'Borrowing from the neat answer given by David Keith:

Transpose[{a[[All,1]],(a+b)[[All,2]]}]==c

True

Alternatively:

a+ArrayFlatten[{{0, List/@b[[All,2]]}}]==c

True

$\endgroup$
1
  • $\begingroup$ And from the answer given by @kglr, Part 2 may also be obtained as follows: SubsetMap[#+RotateRight[#,2]&, a, {All,2}]==c $\endgroup$
    – user1066
    May 27 '20 at 13:53
5
$\begingroup$
SubsetMap[Reverse, a, {All, 2}] == b
True
SubsetMap[# + Reverse @ #&, a, {All, 2}] == c
True

Or get b and c in a single step:

Rest @ FoldList[SubsetMap[#2, #, {All, 2}] &, a, {Reverse, # + Reverse @ # &}] == {b, c}
True
$\endgroup$
4
$\begingroup$

Here's a one-liner:

Transpose@MapAt[# + RotateRight[#, 2] &, Transpose[a], 2]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.