1
$\begingroup$

This question already has an answer here:

Im new to mathematica ( from a python background) so apologies if this is easy.

I have four lists of equal length from a data set. I would like to iterate through each of the lists and apply a function, then return the values to a list. I have come across the Do command but can't seem to figure it out for multiple variables.

Is there a way to use this or a better way.

a_1 = {1,2,3,4,5,6,7,8,9,10
a_2 = {2,3,4,5,6,7,8,9,10,11}
a_3 = {10,11,12,13,14,15,16,17,18,19,20}
a_4 = {2,4,6,8,10,12,14,16,18,20}

z1[x_,y_,z_,k_] = A*x + B*y + C*z + D*k

I am trying to get an output equivalent to this:

 result =  {z1[1,2,10,2], z1[2,3,10,4], z1[3,4,11,6] ...}

What is the easiest way to go about this?

$\endgroup$

marked as duplicate by Kuba list-manipulation Aug 16 '16 at 20:21

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    $\begingroup$ They are not the same length, but take a look at MapThread. $\endgroup$ – Kuba Aug 16 '16 at 19:18
  • 2
    $\begingroup$ Just a hint: don't use underline (_) on your variable names. Unlike in many other languages, it has a special meaning (Blank, which is used on pattern matching.) $\endgroup$ – kirma Aug 16 '16 at 19:22
  • 3
    $\begingroup$ Make sure the lists have the same length (your a_3 has 11 elements, not 10). Rename a_i into ai and then run z1 @@@ Transpose@{a1, a2, a3, a4} $\endgroup$ – BlacKow Aug 16 '16 at 19:43
  • 2
    $\begingroup$ Also it should probably be z1[x_,y_,z_,k_] := A*x... the : is important $\endgroup$ – BlacKow Aug 16 '16 at 19:52
  • 3
    $\begingroup$ Note that both C and D are reserved symbols in Mathematica. Good practice in Mathematica is to never use capitalized words/symbols for user-defined variables/functions. In this case, use a, b, c, d instead of A, B, C, D. $\endgroup$ – march Aug 16 '16 at 20:02
2
$\begingroup$

Here are some solutions (from comments and alternatives).

If we define your lists as

a[1] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
a[2] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11} 
a[3] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20} 
a[4] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}

and your function as

z1[x_, y_, z_, k_] := b*x + c*y + d*z + e*k

(so as not to conflict with the the symbol a associated with your lists), you can do:

BlackKow

z1 @@@ Transpose@{a[1], a[2], a[3], a[4]}
z1 @@@ Transpose@Array[a, 4]
(* {b + 2 c + 11 d + 2 e, 2 b + 3 c + 12 d + 4 e, 3 b + 4 c + 13 d + 6 e,
    4 b + 5 c + 14 d + 8 e, 5 b + 6 c + 15 d + 10 e, 6 b + 7 c + 16 d + 12 e,
    7 b + 8 c + 17 d + 14 e, 8 b + 9 c + 18 d + 16 e, 9 b + 10 c + 19 d + 18 e,
    10 b + 11 c + 20 d + 20 e} *)

Kuba

MapThread[z1, Array[lst, 4]]

Using Table:

Table[z1[lst[1][[j]], lst[2][[j]], lst[3][[j]], lst[4][[j]]], {j, 1, Length@lst[1]}]
$\endgroup$

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