4
$\begingroup$

I have two lists, for example (the real lists are much longer):

list1 = {1, 2, 3, 4, 5, 6, 7};
list2 = {9, 10, 11, 12, 13, 14, 15};

I want to create a single list by adding together different elements from different places in each list. For example,

list3 = (list1i+1 + list1i-1) * (list2i+1 + list2i-1)

where $i$ is the location of the number in the list, e.g. in list2, 12 would be $i=4$. I realize the first and last entries in list3 would either be wrong or non-existent. For example, the 2nd item in list3 would be $(3+1)(11+9)$ and the 3rd item would be $(4+2)(12+10)$.

I hope that makes sense and I appreciate any help.

$\endgroup$
1
  • $\begingroup$ What do you expect for the first element in list3? $\endgroup$
    – DavidC
    Commented Oct 30, 2013 at 16:28

6 Answers 6

4
$\begingroup$

This will do it:

(list1[[3 ;;]] + list1[[;; -3]]) (list2[[3 ;;]] + list2[[;; -3]])

{80, 132, 192, 260, 336}

The smallest value of i has to be 2, and therefore list1[3;;]] represents all values the list of i+1 can assume. Similarly for i-1. The syntax is explained in the documentation for Part.

$\endgroup$
2
  • $\begingroup$ list1[[;; Length[list1] - 2]] can be written as list1[[;; -3]] $\endgroup$ Commented Oct 30, 2013 at 16:20
  • $\begingroup$ @SimonWoods Ty. $\endgroup$
    – C. E.
    Commented Oct 30, 2013 at 16:21
3
$\begingroup$

Or this:

Times @@ (ListCorrelate[{1, 0, 1}, #, {2, -2}, 0] & /@ {list1, list2})

(* {20, 80, 132, 192, 260, 336, 84} *)
$\endgroup$
3
$\begingroup$
a = {1, 2, 3, 4, 5, 6, 7};
b = {9, 10, 11, 12, 13, 14, 15};

With[{f = (Drop[#, 2] + Drop[#, -2] &)}, f@a f@b]

{80, 132, 192, 260, 336}

$\endgroup$
2
$\begingroup$

Another way of doing it

list3 = (RotateLeft[list1]+RotateRight[list1])*(RotateLeft[list2]+RotateRight[list2])
$\endgroup$
1
$\begingroup$

Another way is to use Table as follows:

l = {list1, list2};

Times @@@ Transpose@(Table[#[[i + 1]] + #[[i - 1]], {i, 2, Length@# - 1}] & /@ l)

(*{80, 132, 192, 260, 336}*)
$\endgroup$
1
$\begingroup$
list1 = {1, 2, 3, 4, 5, 6, 7};
list2 = {9, 10, 11, 12, 13, 14, 15};

Using ReplaceList:

a1 = Total /@ ReplaceList[list1, {g___, h_, i_, j_, k___} :> {h, j}];
a2 = Total /@ ReplaceList[list2, {g___, h_, i_, j_, k___} :> {h, j}];
a1 a2

Using Partition:

a1 = {First@#, Last@#} & /@ Partition[list1, 3, 1] // Map[Total];
a2 = {First@#, Last@#} & /@ Partition[list2, 3, 1] // Map[Total];
a1 a2

Using MovingMap:

a1 = MovingMap[Total@{First@#, Last@#} &, list1, 2];
a2 = MovingMap[Total@{First@#, Last@#} &, list2, 2];
a1 a2

A variation that can allow for more lists:

MovingMap[Total@{First@#, Last@#} &, #, 2] & /@ {list1, list2} // 
 Apply[Times]

Result:

{80, 132, 192, 260, 336}

$\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.