Re: Newbie question: pairswise function application
- To: mathgroup at smc.vnet.net
- Subject: [mg23869] Re: [mg23857] Newbie question: pairswise function application
- From: Andrzej Kozlowski <andrzej at bekkoame.ne.jp>
- Date: Thu, 15 Jun 2000 00:51:07 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
on 6/12/00 2:17 PM, Sidney Cadot at sidney at janis.pds.tudelft.nl wrote:
> Hi,
>
> Wandering through the 1500-odd pages of the Mathematica book, I can't
> find the solution to the following rather silly problem:
>
> I have a list L consisting of (a lot of) integers, and I want to apply a
> function f to all pairs of numbers; furthermore, I don't want to
> calculate both f[a,b] and f[b,a]:
>
> L = {1,5,19,100};
>
> ... and I want:
>
> { f[1,5], f[1,19], f[1,100], f[5,19], f[5,100], f[19,100] }
>
> Can anyone please tell me how to do this? I'd prefer a smart solution
> (i.e., not just generating all pairs, then throwing away a lot of them)
> since my lists tend to get rather large.
>
> Thanks in advance,
>
> Sidney Cadot
> sidney at janis.pds.twi.tudelft.nl
>
There is already such a faunction in the package
DiscreteMath`Combinatorica`. It is called KSubsets:
<< DiscreteMath`Combinatorica`
In[2]:=
f @@@ KSubsets[{1, 5, 19, 100}, 2]
Out[2]=
{f[1, 5], f[1, 19], f[1, 100], f[5, 19], f[5, 100], f[19, 100]}
I do not know how fast this is (functions in this package tend to be not
teribly fast since it has not been significantly updated for a long time)
but it uses backtracking so it should do better than making a list of all
pairs and throwing away some. There is actually a vast number of ways to
program something like this. I shall not try to consider efficiency (there
are regular contributors to this list who know a lot more about this aspect
than me and I expect some of them will contribute their versions) but
instead give an example of the kind of Mathematica programming style which
is the reason why I think Mathematica is such a fantastic programming
language for a mathematician:
In[1]:=
L = {1, 5, 19, 100};
In[2]:=
Clear[myfunction]
In[3]:=
myfunction[i_, j_] /; i >= j := Sequence[];
myfunction[i_, j_] /; i < j := f[i, j]
In[5]:=
Distribute[myfunction[L, L], List]
Out[5]=
{f[1, 5], f[1, 19], f[1, 100], f[5, 19], f[5, 100], f[19, 100]}
--
Andrzej Kozlowski
Toyama International University, JAPAN
For Mathematica related links and resources try:
<http://www.sstreams.com/Mathematica/>