Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I made this function:

f[g_] := Table[{ToExpression[ToString[x] <> ToString[n]], 1, 3}, {n, 1, g}]

When I evaluate the function with some g (say 8), I'll have this output:

{{x1, 1, 3}, {x2, 1, 3}, {x3, 1, 3}, {x4, 1, 3}, {x5, 1, 3}, {x6, 1, 3}, {x7, 1, 3}, {x8, 1, 3}}

When I add flatten to the function:

f[g_] := Flatten[Table[{ToExpression[ToString[x] <> ToString[n]], 1, 3}, {n, 1, g}]]

I'll have:

{x1, 1, 3, x2, 1, 3, x3, 1, 3, x4, 1, 3, x5, 1, 3, x6, 1, 3, x7, 1, 3, x8, 1, 3}

When I actually want:

{x1, 1, 3}, {x2, 1, 3}, {x3, 1, 3}, {x4, 1, 3}, {x5, 1, 3}, {x6, 1, 3}, {x7, 1, 3}, {x8, 1, 3}

I have also tried to use the Flatten[] with a level:

f[g_] := Flatten[Table[{ToExpression[ToString[x] <> ToString[n]], 1, 3}, {n, 1, g}], 1]

But I was unable to do it. What's happening? I could do it with string manipulation, but I guess there might be a way for Flatten[] to work.

I'm trying to do this:

ArrayPlot[Table[RandomChoice[{q1, q2, q3} -> Range[1, 3]], {q1, 1, 3}, {q2, 1, 3}, {q3, 1, 3}], Mesh -> True, MeshStyle -> Black]

Where the result of the function is going to replace the {q1, 1, 3}, {q2, 1, 3}, {q3, 1, 3}.

share|improve this question
    
What you want is Sequence not Flatten. –  rcollyer Apr 3 '13 at 20:48
    
With an Evaluate thrown in to stop Table from complaining. –  rcollyer Apr 3 '13 at 20:48
    
I naively learned to go down some levels on a list with Flatten. –  Vÿska Apr 3 '13 at 20:49
    
This is the output: Sequence[{{x1, 1, 3}, {x2, 1, 3}, {x3, 1, 3}, {x4, 1, 3}, {x5, 1, 3}, {x6, 1, 3}, {x7, 1, 3}, {x8, 1, 3}}] –  Vÿska Apr 3 '13 at 20:51
    
Not quite as simple as I implied, but close. You want to replace the Head of your list with Sequence, so you want to Apply Sequence to Table, e.g. Sequence @@ Table[...]. –  rcollyer Apr 3 '13 at 20:52

1 Answer 1

Flatten only restructures the internals of an expression. What you want is to replace the Head of the expression with Sequence. So, change your definition of f to

f[g_] := Sequence @@ Table[{ToExpression[ToString[x] <> ToString[n]], 1, 3}, {n, 1, g}]

Where Apply (@@) is used to change the Head from List to Sequence. Now, to use it within another Table, you need to Evaluate it:

Table[..., Evaluate[ f[...] ]]

This is because Table has the HoldAll attribute.

Edit: Alternatively, leave the definition of f as you have it, but move the Sequence into the outer Table, as follows:

Table[..., Evaluate[ Sequence @@ f[...] ] ]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.