2
$\begingroup$

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?

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

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}]]
$\endgroup$
2
$\begingroup$

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}}}*)
$\endgroup$
1
$\begingroup$
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}}} *)
$\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.