2
$\begingroup$

I have two multi-dimensional lists, for example:

ff = {{{3, 2}, {4, 2}, {8, 6}}}
ff2 = {{{3, 7}, {4, 1}, {8, 4}}}

I would like to subtract them but only in the second element, I want to obtain

ff2 - ff = {{{3, 5}, {4, -1}, {8, -2}}}

but I obtain

f2 - ff = {{{0, 5}, {0, -1}, {0, -2}}}

How can I achieve this?

$\endgroup$
6
  • $\begingroup$ If the first elements of each pair are not equal, what should happen? Or will that never happen? $\endgroup$
    – eyorble
    Oct 21, 2023 at 21:38
  • $\begingroup$ It will never happen $\endgroup$ Oct 21, 2023 at 21:50
  • 3
    $\begingroup$ MapThread[#1 - #2*{0, 1} &, {ff, ff2}, 2]? $\endgroup$
    – ydd
    Oct 21, 2023 at 21:57
  • $\begingroup$ @ydd thank you. It seems to work. What does the last 2 stand for? $\endgroup$ Oct 21, 2023 at 22:00
  • $\begingroup$ It specifies the Level of ff and ff2 to which #1 - #2*{0, 1} & is applied $\endgroup$
    – ydd
    Oct 21, 2023 at 22:02

6 Answers 6

4
$\begingroup$
ff2 - Threaded[{0, 1}] ff
{{{3, 5}, {4, -1}, {8, -2}}}
$\endgroup$
2
$\begingroup$
ff = {{{3, 2}, {4, 2}, {8, 6}}};
ff2 = {{{3, 7}, {4, 1}, {8, 4}}};

1.

res = 
  Transpose[{ff2[[1]], ff[[1]]}] /. {{x_, a_}, {_, b_}} :> {x, a - b}

{{3, 5}, {4, -1}, {8, -2}}

2.

res =
 KeyValueMap[List] @
  GroupBy[Flatten[{ff, ff2}, 2], First -> Last, First @* Differences]

{{3, 5}, {4, -1}, {8, -2}}

3.

res =
 KeyValueMap[List] @
  Merge[First @* Differences] @ MapApply[Rule] @ Flatten[{ff, ff2}, 2]

{{3, 5}, {4, -1}, {8, -2}}

If you want the outermost brackets:

List @ res

{{{3, 5}, {4, -1}, {8, -2}}}

$\endgroup$
1
$\begingroup$
Clear[subtract];
subtract[x_, y_] := If[x == y, x, x - y];
SetAttributes[subtract, Listable]
subtract[ff2, ff]

{{{3, 5}, {4, -1}, {8, -2}}}

$\endgroup$
1
  • $\begingroup$ Clear[subtract]; subtract = Function[{x, y}, If[x == y, x, x - y], Listable]; subtract[ff2, ff] $\endgroup$
    – cvgmt
    Oct 22, 2023 at 2:34
1
$\begingroup$
ff3 = ff;
ff3[[All, All, 2]] //= ff2[[All, All, 2]] - # &;
ff3
{{{3, 5}, {4, -1}, {8, -2}}}
$\endgroup$
1
$\begingroup$
ReplacePart[ff, p : {_, _, 2} :> ff2[[## & @@ p]] - ff[[## & @@ p]]]
{{{3, 5}, {4, -1}, {8, -2}}}
$\endgroup$
1
$\begingroup$
ff2-ff.{{0,0},{0,1}}

(* {{{3,5},{4,-1},{8,-2}}} *)

Or

ff2 - Map[{0,Last@#}&, ff,{2}]

(* {{{3,5},{4,-1},{8,-2}}} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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