Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Loop programming; how do i do this ???

  • To: mathgroup at smc.vnet.net
  • Subject: [mg96116] Re: Loop programming; how do i do this ???
  • From: Peter Pein <petsie at dordos.net>
  • Date: Thu, 5 Feb 2009 04:41:03 -0500 (EST)
  • References: <gmbr29$igp$1@smc.vnet.net>

plzhlp schrieb:
> I need to implement a function into my notebook but am having great difficulties even getting started (i'm new to mathematica and programming in general)
> 
> The function accepts a 1d array (of variable length) of integers
> 
> which will refer to a 2d array of constants, of which all need to be tested against eachother.
> 
> for example:
> 
> 1DArrayVar = {2, 4, 5}
> 
> 2DArrayCon = {
>              {a1,b1,c1},
>              {a2,b2,c2},
>              {a3,b3,c3},
>              {a4,b4,c4},
>              {a5,b5,c5}
>              }
> 
> Function[1DArrayVar]
> 
> in this scenario will test:
> 
> Do[
>   Do[
>     Do[
> 
> TEST[2DArrayCon[[2,x]],2DArrayCon[[4,y]],2DArrayCon[[5,z]]]
> 
>     , {x, Length[DArrayCon[[2]]]
>   , {y, Length[DArrayCon[[4]]]
> , {z, Length[DArrayCon[[5]]]
> 
> 
> So basically the problem is that i need a variable amount of nested loops, as the length of 1DArrayVar will always be unknown.
> 
>>From some research on the internet i've learned a recursive algorithm might be the solution, but i am completely lost on how to start --
> 
> any tips would be really appreciated !
> 

Hi,

I would use

In[1]:=
D1ArrayVar = {2, 4, 5};
D2ArrayCon = {{a1, b1, c1}, {a2, b2, c2}, {a3, b3, c3}, {a4, b4, c4},
    {a5, b5, c5}};
In[3]:=
Apply[TEST, Distribute[D2ArrayCon[[D1ArrayVar]], List], {1}]
Out[3]=
{TEST[a2, a4, a5], TEST[a2, a4, b5], TEST[a2, a4, c5], TEST[a2, b4, a5],
 TEST[a2, b4, b5], TEST[a2, b4, c5], TEST[a2, c4, a5], TEST[a2, c4, b5],
 TEST[a2, c4, c5], TEST[b2, a4, a5], TEST[b2, a4, b5], TEST[b2, a4, c5],
 TEST[b2, b4, a5], TEST[b2, b4, b5], TEST[b2, b4, c5], TEST[b2, c4, a5],
 TEST[b2, c4, b5], TEST[b2, c4, c5], TEST[c2, a4, a5], TEST[c2, a4, b5],
 TEST[c2, a4, c5], TEST[c2, b4, a5], TEST[c2, b4, b5], TEST[c2, b4, c5],
 TEST[c2, c4, a5], TEST[c2, c4, b5], TEST[c2, c4, c5]}

or with a shorter list of indices:

In[4]:=
Apply[TEST, Distribute[D2ArrayCon[[{1, 4}]], List], {1}]
Out[4]=
{TEST[a1, a4], TEST[a1, b4], TEST[a1, c4], TEST[b1, a4], TEST[b1, b4],
 TEST[b1, c4], TEST[c1, a4], TEST[c1, b4], TEST[c1, c4]}


  • Prev by Date: Dashing (Again)
  • Next by Date: Re: Changing Line Color in Plot
  • Previous by thread: Re: Loop programming; how do i do this ???
  • Next by thread: Re: Loop programming; how do i do this ???