## Is there any function that creates an array from 1 to n, repeating each value m times?

2

I am trying to implement SparseArray, using the function With to give the condition for different matrix elements. I would need a function f, that instead of doing what Mod does,

Mod[{1, 2, 3, 4, 5, 6}, 3, 1]

{1, 2, 3, 1, 2, 3}

I would like to have:

f[{1, 2, 3, 4, 5, 6}, 3, 1]

{1, 1, 1, 2, 2, 2}

So that,

f[1,3,1]

1

and

f[4,3,1]

2

Does such a function f exist?

Quotient does the job! – Ali – 2013-05-27T15:28:22.047

Since everybody's going nuts with alternative solutions: one could also use Fold[]+Riffle[] for the task... – J. M.'s ennui – 2013-05-28T04:16:10.733

10

Quotient[Range[6], 3, 1] + 1
{1, 1, 1, 2, 2, 2}

Precisely, thanks @J.M you are genius, holly smokes!!:) – Mencia – 2013-05-27T15:34:54.600

how do you give format to the question? – Mencia – 2013-05-27T15:41:29.913

See this for stuff on formatting.

– J. M.'s ennui – 2013-05-27T15:43:44.130

3

Here's a variation on partial81's answer:

reps[n_, m_] := Flatten[ConstantArray[#, m] & /@ Range[n]]

This creates an array from 1 to $n$, repeating each value $m$ times. For example:

reps[5,3]
{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5}

2

Another way to do this:

q = Range[6];
m = 3;
Round[(q + 1)/m]

{1, 1, 1, 2, 2, 2}

Here's the same kind of idea made into a function (it's a little simpler to use Ceiling than Round: make $m$ copies of each number from 1 to $n$

reps2[n_, m_] := Ceiling[Range[n m]/m]

reps2[3,4]
{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}

2

arrayFunc[n_, m_] := Flatten[Table[ConstantArray[i, m], {i, 1, n}]]

E.g. arrayFunc[5, 2] gives {1, 1, 2, 2, 3, 3, 4, 4, 5, 5}.

But I admit that I am confused by our definition of your f.

1

Here are a couple more ways, using Table and Array.

In each case,

r: the number of repeats n: the range from 1 to n

f[r_,n_]:=Table[i,{i,r},{n}]//Flatten
f[5, 3]

{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5}

g[r_,n_]:=Array[#&,{r,n}]//Flatten
g[5, 3]

{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5}

1

Yet more ways:

With[{n = 10, m = 3}, Flatten@Transpose@ConstantArray[Range[n], m]]

Or for those who prefer inefficiency:

With[{n = 10, m = 3}, Flatten@Cases[Range[n], x_ :> ConstantArray[x, m]]]