1
$\begingroup$

I have a function of two arguments, f[x_,y_], and I want to sum the value of this function for a number of input tuples {x,y} which are in a list. I don't see any way of doing this with Sum. I could write a loop but I'd like to know if there's a better way.

Edit:

Specifically, my function is actually a matrix where the elements are determined by x and y.

$\endgroup$
2
$\begingroup$

You can just Apply function f:

f[x_, y_] := (x + y)^2;
a = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}};

f @@@ a
(* {9, 25, 49, 81, 121} *)

f @@@ a // Total
(* 285 *)
$\endgroup$
  • $\begingroup$ sorry i should have clarified, what if my function is a matrix of functions? Say, f[x_,y_] = {{a[x,y],b[x,y]},{c[x,y],d[x,y]}} $\endgroup$ – Kai Jan 31 '18 at 22:07
  • $\begingroup$ @Kai It will still work. The result will just be a matrix with sum of elements. $\endgroup$ – m0nhawk Jan 31 '18 at 22:14
  • $\begingroup$ Thanks, I was having another issue that was preventing it from working but I've got it now $\endgroup$ – Kai Feb 1 '18 at 1:05
  • $\begingroup$ I have a further question, what if my function is f[x,y,A], where A is an extra vector of parameters? I want to be able to use this in a loop where each time the values in A are updated, but I always pass the same list to the x,y arguments $\endgroup$ – Kai Feb 1 '18 at 1:39
  • 1
    $\begingroup$ I found I can define f[{x_,y_},A_] then perform f[#,Avalues]&/@tuples which seems to work fine. $\endgroup$ – Kai Feb 1 '18 at 2:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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