Re: Lists of all values of a two-variable function

• To: mathgroup at smc.vnet.net
• Subject: [mg64769] Re: Lists of all values of a two-variable function
• From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
• Date: Thu, 2 Mar 2006 06:48:42 -0500 (EST)
• Organization: The Open University, Milton Keynes, UK
• References: <du3vcn\$mjd\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```José Carlos Santos wrote:
> Hi all,
>
> I would like to do this: given a function _f_ in two variables and two
> lists l1 and l2, to get the list of all values f[a,b] with _a_ in l1 and
> _b_ in l2, with all duplicated values removed. How do I do that?
>
> The closest thing that I am able to do is:
>
> Table[f[l1[[i]],l2[[j]]],{i,1,Length[l1]},{j,1,Length[l2]}]
>
> but, of course:
>
> 1) what I get is a list of lists;
>
> 2) I eventually get duplicated values.
>
> Best regards,
>
> Jose Carlos Santos
>
Hi Jose Carlos,

You could try one of the following approaches among many others. First,
starting with your method using *Table* and say that l1, l2 and f are
equal to

In[1]:=
l1 = {1, 2, 3};
l2 = {2, 3, 4, 5};
f[a_, b_] := a^2 + b^2;

respectively, you can get the type of result you are looking for by
wrapping the list of lists within a *Union* and *Flatten* commands

In[4]:=
Union[Flatten[Table[f[l1[[i]], l2[[j]]],
{i, 1, Length[l1]}, {j, 1, Length[l2]}]]]

Out[4]=
{5,8,10,13,17,18,20,25,26,29,34}

No duplicates and only one level. Hoe does it work?
First, *Table* yields a list of lists

In[5]:=
Table[f[l1[[i]], l2[[j]]], {i, 1, Length[l1]},
{j, 1, Length[l2]}]

Out[5]=
{{5,10,17,26},{8,13,20,29},{13,18,25,34}}

Then, *Flatten* returns a simple list, unsorted and with duplicates

In[6]:=
Flatten[%]

Out[6]=
{5,10,17,26,8,13,20,29,13,18,25,34}

Finally, *Union* sorts the list and discard any duplicates

In[7]:=
Union[%]

Out[7]=
{5,8,10,13,17,18,20,25,26,29,34}

Another approach would be to use an outer product as in

In[8]:=
Outer[f, l1, l2]//Flatten//Union

Out[8]=
{5,8,10,13,17,18,20,25,26,29,34}

since *Outer* yields

In[9]:=
Outer[f, l1, l2]

Out[9]=
{{5,10,17,26},{8,13,20,29},{13,18,25,34}}

You could try also the *Tuple* function with a slightly modified version
of the function f

In[10]:=
Tuples[{l1,l2}]

Out[10]=
{{1,2},{1,3},{1,4},{1,5},{2,2},{2,3},{2,4},{2,5},{3,2},{3,3},{3,4},{3,5}}

In[11]:=
f[{a_,b_}]:=a^2+b^2;

In[12]:=
f/@Tuples[{l1,l2}]//Union

Out[12]=
{5,8,10,13,17,18,20,25,26,29,34}

Best regards,
/J.M.

```

• Prev by Date: Rayica and LensLab for Mathematica now available
• Next by Date: Re: Nonlinear Fit of Complex functions
• Previous by thread: Re: Lists of all values of a two-variable function
• Next by thread: Derivation of Sums of Functions