2
$\begingroup$

I would like to initialize this kind of vector : {0,0,1,1,0,1,0,1,1,1,1,1} with Table.
I tried Table[{x, y, 1}, {y, 0, 1, 1}, {x, 0, 1, 1}] but it outputs {{0,0,1},{1,0,1},{0,1,1},{1,1,1}}.
What is the right method to correctly initialize my vector without creating sub-lists ?

$\endgroup$
5
$\begingroup$
Table[{x, y, 1}, {y, 0, 1, 1}, {x, 0, 1, 1}] // Flatten

gives

{0,0,1,1,0,1,0,1,1,1,1,1}
$\endgroup$
3
$\begingroup$

Consider also:

Flatten @ Array[{#2, #, 1} &, {2, 2}, 0]
{0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1}

This is faster than Table, if applicable:

n = 2200;

Table[{x, y, 1}, {y, 0, n}, {x, 0, n}] // Flatten // Length // Timing
Array[{#2, #, 1} &, {n, n} + 1, 0]     // Flatten // Length // Timing
{1.435209, 14533203}

{0.280802, 14533203}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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