Group Abstract Group Abstract

Message Boards Message Boards

0
|
6.9K Views
|
5 Replies
|
7 Total Likes
View groups...
Share
Share this post:

[?] Get the value of yi given the value of xi of a list={{x1,y1},...};?

Posted 9 years ago

Greetings,

My doubt is: If a have a list list={{x1,y1},{x2,y2},{x3,y3},...{xi,yi},...,{xn,yn}}; what function do I use to get the value of yi given the value of xi?

Thanks

POSTED BY: Lucas Aquino
5 Replies

I think the most general way is Association functionality. Given

list = Table[{k, 21 k}, {k, 7}]

{{1, 21}, {2, 42}, {3, 63}, {4, 84}, {5, 105}, {6, 126}, {7, 147}}

try this:

Association[Rule @@@ list][4]

84

In this case xi=4 is called the Key. But it is assumed that all Keys are unique.

POSTED BY: Vitaliy Kaurov
Posted 9 years ago

Another approach:

In[1]:= theList = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}, {x3, y17}};

In[2]:= f[alist_, y_] := Cases[alist, {_, y}]

In[3]:= f[theList, y17]

Out[3]= {{x3, y17}}
POSTED BY: Hans Milton
Posted 9 years ago

One way is the following:

list = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}, {x3, y17}};
Select[list, #[[1]] == x3 &][[All, 2]]
(* {y3, y17} *)
POSTED BY: Jim Baldwin
Posted 9 years ago

Not that it is of any importance, but I just saw/realized that Lucas asked for a function that returned the second element, given the first. And I mistook it for the other way around. So this is just to set my record straight :)

In[1]:= theList = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}, {x3, y17}};

In[2]:= f[alist_, x_] := Cases[alist, {x, _}]

In[3]:= f[theList, x3]

Out[3]= {{x3, y3}, {x3, y17}}
POSTED BY: Hans Milton
Posted 9 years ago

Thanks! You've really helped!

POSTED BY: Lucas Aquino
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard