# How to evaluate an expression over a particular list of tuples?

NOTE: This question is very similar to this one but I realized reading at the answers that I made a mistake in the equation AND I was not clear enough about what I need (my apologies):

I want to evaluate this expression:

expr1[i_,j_] = β[j]*ϕ[i, j]* C[i]


For $i=1:4, \, j=1:4$ with $i \ne j$, so over this list of tuples:

A = {{1, 2}, {1, 3}, {1, 4}, {2, 1}, {2, 3}, {2, 4}, {3, 1}, {3, 2}, {3, 4}, {4, 1}, {4, 2}, {4, 3}}.


so that I get:

expr1[1,2] = β*ϕ[1,2]*C
expr1[1,3] = β*ϕ[1,3]*C
...
expr1[4,3] = β*ϕ[4,3]*C


I have tried the following code:

expr2ind[i_, j_] :=
dInf2[i, j] = β[
j]*(ψ[i, j] Boole[i != j]*
R[i] + ϕ[i, j] Boole[i != j]* C[i]) - γ[j]*
Inf2[i, j] Boole[i != j]

Do[expr2ind[i, j][];
CellPrint@Cell[BoxData@ToBoxes@expr2ind[i, j], "Input"], {i, 1,
4}, {j, 1, 4}]


This works well, except for the fact that the "Do" loop still computes the pairs (i,i), getting the following message: Part::partd: Part specification 0 is longer than depth of object. >>

and getting a

0


which I am trying to avoid. Basically, I want to know if there is a way to iterate over a particular set of tuples in Mathematica, equivalent to Python or Matlab. Thanks

• Closely related: (9537) May 28, 2015 at 1:38

expr1 @@@ DeleteCases[Tuples[Range @ 4, {2}], {a_, a_}]


{C β ϕ[1, 2], C β ϕ[1, 3], C β ϕ[1, 4], C β ϕ[2, 1], C β ϕ[2, 3], C β ϕ[2, 4], C β ϕ[3, 1], C β ϕ[3, 2], C β ϕ[3, 4], C β ϕ[4, 1], C β ϕ[4, 2], C β ϕ[4, 3]}

where @@@ is a shortcut for Apply at level {1}.

If your intention is to define expr1 for the input tuples it would be:

(expr1[#1,#2]=β[#2]*ϕ[#1, #2]* C[#1])& @@@
DeleteCases[Tuples[Range @ 4, {2}], {a_, a_}]

• Thanks, could you please explain the difference between the first and the second options? It is not obvious to me. May 27, 2015 at 18:16
• The first option literally does what's in the title of your question: it evaluates a function over a set of tuples. Your question body itself seemed to suggest that you wanted to set (define) expr[1,1], expr[1,2] etc. So, this is what the second option does. It uses a pure function to do this. May 27, 2015 at 18:54
expr2ind[i_, j_] := β[j](ψ[i, j] Boole[i != j] R[i] +
ϕ[i, j] Boole[i != j] C[i]) - γ[j] Inf2[i, j] Boole[i != j]

pairs = Join @@ {#, Reverse /@ #} &@Subsets[Range, {2}];
expr2ind @@@ pairs Sum[expr2ind @@ k, {k, pairs}] Changing the arguments in your function to a list...

expr1[{i_, j_}] := β[j]*ψ[i, j]*C[i]
Map[expr1[#] &, Subsets[Range, {2}]] // TableForm

C β ψ[1,2]
C β ψ[1,3]
C β ψ[1,4]
C β ψ[2,3]
C β ψ[2,4]
C β ψ[3,4]


Subsets will avoid repeating the same index in the argument of expr1.