2
$\begingroup$

Here's what I know how to do:

f[x_] := x^2 - 4 x + 4
Ordering[f /@ {1, 2, 3}]

This will evaluate f at each point and rank their sizes.

Here's what I really have:

g[x_,y_]:=(x-y)^2 - 4(x-y)+4

I'd like to do the same type of Ordering as above but with a fixed value of y. Currently, I'm doing it this way

yfixed=0;
f[x_]:=g[x,yfixed]
Ordering[f /@ {1, 2, 3}]

There's got to be a better way without creating the f function. Something like Ordering[g[_,0]/@{1,2,3}]. What's the technique here that I don't know?

$\endgroup$
  • $\begingroup$ Ordering[Function[x, g[x, yfixed]] /@ {1, 2, 3}]? $\endgroup$ – J. M. will be back soon Jun 6 '15 at 4:08
  • $\begingroup$ @J. M.: beat me to it. Unfortunately, I already posted the answer! (Without paying attention to the fact that you'd already commented, of course. Does that mean I should remove it? I'm not sure of the etiquette, here.) $\endgroup$ – march Jun 6 '15 at 4:11
  • $\begingroup$ It's good that you wrote an answer, @march (I have upvoted it), but I believe OP will benefit greatly from you showing versions with and without Slot. :) $\endgroup$ – J. M. will be back soon Jun 6 '15 at 4:14
  • $\begingroup$ I'm new here, @J. M., so I'm unsure of etiquette in general. Thanks for the recommendation: I'll edit the post. $\endgroup$ – march Jun 6 '15 at 4:43
3
$\begingroup$

Updated to provide more details (per a suggestion in the comments). In addition, the implementation using Outer was wrong

A simple extension of what you've written will do the trick:

Ordering[Function[x,g[x,yFixed]] /@ {1,2,3}]

or more simply,

Ordering[g[#,yFixed]& /@ {1,2,3}]

where g[#,yFixed]& is essentially shorthand for Function[x,g[x,yFixed]].

The reason your original idea doesn't work is that Map (or /@) applies the left-hand side to each element of the right-hand in a literal fashion. For instance, the first element of the list is g[_,0][1]. In this case, g[_,0] gets evaluated first by plugging in _ for x and 0 for y. The resulting expression is then applied to 1, yielding (4 - 4 _ + _^2)[1], which is a very strange expression.

Alternatively, you could use Outer, although maybe this is overkill for this problem. On the other hand, it would allow you to do many values of y at once, by replacing the third argument of Outer with the list of y's and mapping Ordering over the result. For your example:

Ordering[Outer[g,{1,2,3},{yFixed}]]

Outer supplies all pairs of elements---the first from the first list, and the second from the second---as inputs to g and forms a list. If you have a list ys={0,4}, you could do

Ordering/@ Transpose[Outer[g,{1,2,3},ys]]
$\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.