3
$\begingroup$

I have a function and $x$-values as a list. How do I construct a list with coordinates $(x_i,y(x_i))$, $i=1, 2, …$

y[x_]:= 2x
x = { -3, 0, 4, 5}

which should be made into

{ {-3,-6}, {0,0}, {4,8}, {5,10} }

Is there some compact command for this? The following works but is perhaps not optimal;

Table[{x[[i]], y[x][[i]]}, {i, 1, Length[x]}]
$\endgroup$
2
  • 4
    $\begingroup$ For example Table[{x, y[x]}, {x, xvalues}] where xvalues = {-3, 0, 4, 5}. This is probably the most semantically appealing option. Another solution is Transpose[{x, y /@ x}] where x is as you defined it. Those are general solutions, in your case you have a listable function, which means that you can also use the slightly simpler Transpose[{x, y[x]}], and if performance matters then this is what you should use. $\endgroup$
    – C. E.
    Jun 28 '20 at 0:11
  • $\begingroup$ Very nice. I agree that the Table variant is the most semantically appealing option but the others worked equally well. $\endgroup$
    – mf67
    Jun 28 '20 at 0:30
4
$\begingroup$

Description

In essence, the solution below employs a pure function. The {#, 2#} defines the form of a sub-list structure where # is a slot. We then use a map /@ to take each element from the list {-3, 0, 4, 5} and plug it into the slot to generate the desired output.

Input

{#, 2 #} & /@ {-3, 0, 4, 5}

Output

{{-3, -6}, {0, 0}, {4, 8}, {5, 10}}

Reference

Pure Functions Map Slot

$\endgroup$
1
  • 1
    $\begingroup$ This is, in addition to C.E.'s suggestions above is also a very 'neat' syntax, with the slight modification of {#, y[#]} & /@ x $\endgroup$
    – mf67
    Jun 28 '20 at 0:29

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.