There are two lists:
list1 = {{1, 2, 4}, {1, 3, 5}, {2, 5, 7}}; list2 = {{1, 2, 7}, {1, 3, 3}, {2, 5, 6}}; How can we subtract the last number of each row in list2 from list1 as
diff = {{1, 2, 3}, {1, 3, -2}, {2, 5, -1}} diff = list1; diff[[All, -1]] = Subtract[list2[[All, -1]], list1[[All, -1]]]; diff {{1, 2, 3}, {1, 3, -2}, {2, 5, -1}}
diff2 = list2; diff2[[All, -1]] -= list1[[All, -1]]; diff2 {{1, 2, 3}, {1, 3, -2}, {2, 5, -1}}
Another solution:
list1 // ReplacePart[ {i_, 3} :> Differences[ {list1, list2}, {1, 0} ][[ 1, i, 3]] ] {{1, 2, 3}, {1, 3, -2}, {2, 5, -1}}
a = {{1, 2, 4}, {1, 3, 5}, {2, 5, 7}}; b = {{1, 2, 7}, {1, 3, 3}, {2, 5, 6}}; Using SubsetMap (new in 12.0)
SubsetMap[Last /@ (b - a) &, a, {All, -1}] {{1, 2, 3}, {1, 3, -2}, {2, 5, -1}}
Try this:
Transpose[ Append[Transpose[list1 ][[1 ;; 2]], Last[Transpose[list2 ] - Transpose[list1 ]]]] (* {{1, 2, 3}, {1, 3, -2}, {2, 5, -1}} *) Have fun!
l1 = {{1, 2, 4}, {1, 3, 5}, {2, 5, 7}}; l2 = {{1, 2, 7}, {1, 3, 3}, {2, 5, 6}}; Using Thread and ReplaceAll:
rep = s_?VectorQ :> If[DuplicateFreeQ[s], Subtract @@ s, s[[1]]]; Thread /@ Thread[{l2, l1}] /. rep (*{{1, 2, 3}, {1, 3, -2}, {2, 5, -1}}*) Or using Map and Thread:
Map[x |-> {Splice@Most@x[[1]], x[[1, 3]] - x[[2, 3]]}, Thread[{l2, l1}]] (*{{1, 2, 3}, {1, 3, -2}, {2, 5, -1}}*) Using MapThread:
Clear["Global`*"]; list1 = {{1, 2, 4}, {1, 3, 5}, {2, 5, 7}}; list2 = {{1, 2, 7}, {1, 3, 3}, {2, 5, 6}}; MapThread[Most@#1~Join~{Last@#2 - Last@#1} &, {list1, list2}] or
MapThread[{#1[[1]], #1[[2]], #2[[3]] - #1[[3]]} &, {list1, list2}] Result:
{{1, 2, 3}, {1, 3, -2}, {2, 5, -1}}