Re: Variable-length list?
- To: mathgroup at smc.vnet.net
- Subject: [mg83493] Re: Variable-length list?
- From: "Szabolcs HorvÃt" <szhorvat at gmail.com>
- Date: Wed, 21 Nov 2007 03:03:33 -0500 (EST)
- References: <fhu73f$71m$1@smc.vnet.net> <4742F526.5020201@gmail.com>
On Nov 21, 2007 3:32 AM, Hoa Bui <hoabui05 at gmail.com> wrote: > Hi, > > Thanks for your comment, but this is not quite what I wanted to do. > I tried to simplify the problem, but basically if I have a vector > v={v[[1]],v[[2]],..v[[n]]} > and each element v[[i]] has a range in which it can vary. I want to be > able to search over all the possible combinations of the v[[i]]. (Each > combination will return a vector, lets call it vi, and I want to use > that vi to do something else.) > The problem is that the number of dimensions (n) is not a fixed > number, I want it to be a variable as well. > > Here's an example: > If n=2, then v={a,b}. Say a={a1,a2} and b={b1,b2,b3}, then the combinations are: > vi={{a1,b1}, {a1,b2}, {a1,b3}, {a2,b1}, {a2,b2}, {a2,b3}} > > If n=3, then v={a,b,c}. Say a={a1,a2}; b={b1,b2,b3}; c={c1,c2}, then I > want to get: > vi={{a1,b1,c1}, {a1,b2,c1}, {a1,b3,c1}, {a2,b1,c1}, {a2,b2,c1}, > {a2,b3,c1}, {a1,b1,c2}, {a1,b2,c2}, {a1,b3,c2}, {a2,b1,c2}, > {a2,b2,c2}, {a2,b3,c2}} > > If n=4, then I'll need another list d to represent my 4th dimension. Well, why didn't you say so in the first place? Take a look at Outer[] In[1]:= f[v_] := Flatten[Outer[List, Sequence @@ v], Length[v] - 1] In[2]:= f[{{a1, a2}, {b1, b2, b3}, {c1, c2}}] Out[2]= {{a1, b1, c1}, {a1, b1, c2}, {a1, b2, c1}, {a1, b2, c2}, {a1, b3, c1}, {a1, b3, c2}, {a2, b1, c1}, {a2, b1, c2}, {a2, b2, c1}, {a2, b2, c2}, {a2, b3, c1}, {a2, b3, c2}} > > You see, it would be easy if n is a fixed number (because then I can > just use Array[] with the specified dimensions {na, nb, nc,...}. But > the trouble is, even the number n of dimensions is a variable. That's why the second argument of Array was taken from the function argument in my last example. Did you try it? In[3]:= g[{dd__Integer}]:=Array[Times,{dd}] In[4]:= g[{3,4}] Out[4]= {{1,2,3,4},{2,4,6,8},{3,6,9,12}} In[5]:= g[{3,4,5}] Out[5]= {{{1,2,3,4,5},{2,4,6,8,10},{3,6,9,12,15},{4,8,12,16,20}},{{2,4,6,8,10},{4,8,12,16,20},{6,12,18,24,30},{8,16,24,32,40}},{{3,6,9,12,15},{6,12,18,24,30},{9,18,27,36,45},{12,24,36,48,60}}} > Obviously, I cannot use For[], because each For[] only solves 1 > dimension so I can only have a fixed number of dimensions searched. > > Is this doable? Everything is doable in Mathematica :-) But For[] is rarely a good way to do things. I hope this helps, Szabolcs