0
$\begingroup$

I am looking for a way that Mathematica quickly evaluate a scalar function $g(x,y)$ given a long list of points {{x_1,y_1},{x_2,y_2},{x_3,y_3},{x_4,y_4},.......}. Can this be done?

I am aware that you can do this easily for the 1-dimensional case, as shown below:

enter image description here

However, Mathematica does not like an input analagous to the above in 2 dimensions or higher, as shown here:

enter image description here

$\endgroup$
4
$\begingroup$

Try

TwoDim={{1,1},{2,3},{3,5},{4,7}};
g[{x_,y_}]:=x^2+y^2;
g/@TwoDim

which instantly returns

{2,13,34,65}

You can also use

Map[g,TwoDim]

and get exactly the same result

$\endgroup$
1
  • $\begingroup$ A key point of this nicely put solution is that the function call must match the input arguments to the declaration. That is, you have to have the same format or the function doesn't match. That is why you saw the line g[<your original input>] - it couldn't match any of the input to your function. $\endgroup$
    – Mark R
    May 1 '20 at 2:19
3
$\begingroup$

The solution shown is fine but if you want to extend it to n-dimensions, try this:

g[a_List] := Total[#^2] & /@ a

Now, if you give this:

nDim = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
g[nDim]
(*{14, 77, 194}*)

It would even work for mixed dimensions within the list.

$\endgroup$

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.