5
$\begingroup$

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}.

$\endgroup$
9
  • $\begingroup$ What you want is Sequence not Flatten. $\endgroup$
    – rcollyer
    Apr 3, 2013 at 20:48
  • $\begingroup$ With an Evaluate thrown in to stop Table from complaining. $\endgroup$
    – rcollyer
    Apr 3, 2013 at 20:48
  • $\begingroup$ I naively learned to go down some levels on a list with Flatten. $\endgroup$
    – Red Banana
    Apr 3, 2013 at 20:49
  • $\begingroup$ 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}}] $\endgroup$
    – Red Banana
    Apr 3, 2013 at 20:51
  • $\begingroup$ 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[...]. $\endgroup$
    – rcollyer
    Apr 3, 2013 at 20:52

1 Answer 1

7
$\begingroup$

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[...] ] ]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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