# Manipulating array

I have got an array like this:

A = {{{1, 4, 5}, {3, 7, 15}}, {{5, 6, 9}, {7, 8, 2}}, {{9, 10,
1}, {11, 12, 3}}}


I make differences in each sublist a following way

Dif = Differences[A, {0, 0, 1}]


and get

 {{{3, 1}, {4, 8}}, {{1, 3}, {1, -6}}, {{1, -9}, {1, -9}}}


Then I want to duplicate the first difference in each sublist, which means I would like to obtain array like this:

 {{{3, 3, 1}, {4, 4, 8}}, {{1, 1, 3}, {1, 1, -6}}, {{1, 1, -9}, {1, 1, -9}}}


Does anyone know how to do it? Is there any function which would help?

• list[[All, All, {1,1,2}]] ? – Yves Klett Oct 22 '14 at 19:18

To preserve the content of the initial comment:

list = {{{3, 1}, {4, 8}}, {{1, 3}, {1, -6}}, {{1, -9}, {1, -9}}};
list[[All, All, {1, 1, 2}]]

(*{{{3, 3, 1}, {4, 4, 8}}, {{1, 1, 3}, {1, 1, -6}}, {{1, 1, -9}, {1,
1, -9}}}*)


For those of the code golf or one-liner persuasion, you can save a whopping two characters by:

list[[;; , ;; , {1, 1, 2}]]


I want to duplicate the first difference in each sublist,

a = {{{1, 4, 5}, {3, 7, 15}}, {{5, 6, 9}, {7, 8, 2}}, {{9, 10, 1}, {11, 12, 3}}}
dif = Differences[a, {0, 0, 1}]

(* {{{3, 1}, {4, 8}}, {{1, 3}, {1, -6}}, {{1, -9}, {1, -9}}} *)

Cases[#, {x_, y_} :> {x, x, y}] & /@ dif
(*{{{3, 3, 1}, {4, 4, 8}}, {{1, 1, 3}, {1, 1, -6}}, {{1, 1, -9}, {1, 1, -9}}}*)

aA = {{{1, 4, 5}, {3, 7, 15}}, {{5, 6, 9}, {7, 8, 2}}, {{9, 10, 1}, {11, 12, 3}}};
dif = Differences[aA, {0, 0, 1}];
(* {{{3, 1}, {4, 8}}, {{1, 3}, {1, -6}}, {{1, -9}, {1, -9}}} *)


My favorite being dif[[All,All,{1,1,2}]] suggested by @Yves in comments, you can also use

Map[ArrayPad[#, {1, 0}, "Fixed"] &, dif, {-2}]
(* {{{3,3,1},{4,4,8}},{{1,1,3},{1,1,-6}},{{1,1,-9},{1,1,-9}}} *)

MapAt[Sequence @@ {#, ##} &, dif, {All, All, 1}]
(* {{{3,3,1},{4,4,8}},{{1,1,3},{1,1,-6}},{{1,1,-9},{1,1,-9}}} *)