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: [mg96099] Re: [mg96071] Loop programming; how do i do this ???
  • From: Sseziwa Mukasa <mukasa at jeol.com>
  • Date: Thu, 5 Feb 2009 04:37:52 -0500 (EST)
  • References: <200902041019.FAA18602@smc.vnet.net>

On Feb 4, 2009, at 5:19 AM, plzhlp wrote:

> 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 !


I assume the function test has some sort of side effect, because the  
return value of a Do expression is Null.

Recursively,

f[constants_,{var_},args__]:=Do[test[args,constants[[var,i]]], 
{i,Length[constants[[var]]]}]

f[constants_,vars_,args__]:=Do[f[constants,Rest[vars],Join 
[{args},constants[[First[vars],i]]]],{i,Length[constants[[First 
[vars]]]]}]

f[constants_,vars_]:=f[constants,vars,{}]

f[constants_,{var_}]:=Do[test[constants[[var,i]]],{i,Length[constants 
[[var]]]}]

I think an iterative version is clearer though:

f[constants_,vars_]:=Module[{indices},Do[test[Sequence@@Table 
[constants[[vars[[j]],indices[j]]],{j,Length[vars]}]],Evaluate 
[Sequence@@Table[{indices[j],Length[constants[[vars[[j]]]]]},{j,Length 
[vars]}]]]]

Regards,

Ssezi


  • Prev by Date: Default Symbol Names in Package Functions
  • Next by Date: Re: Loop programming; how do i do this ???
  • Previous by thread: Loop programming; how do i do this ???
  • Next by thread: Re: Loop programming; how do i do this ???