2
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ Quotient does the job! $\endgroup$ – Ali May 27 '13 at 15:28
  • $\begingroup$ Since everybody's going nuts with alternative solutions: one could also use Fold[]+Riffle[] for the task... $\endgroup$ – J. M. is away May 28 '13 at 4:16
10
$\begingroup$

How about this?

Quotient[Range[6], 3, 1] + 1
   {1, 1, 1, 2, 2, 2}
$\endgroup$
  • $\begingroup$ Precisely, thanks @J.M you are genius, holly smokes!!:) $\endgroup$ – Mencia May 27 '13 at 15:34
  • $\begingroup$ how do you give format to the question? $\endgroup$ – Mencia May 27 '13 at 15:41
  • $\begingroup$ See this for stuff on formatting. $\endgroup$ – J. M. is away May 27 '13 at 15:43
3
$\begingroup$

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}
$\endgroup$
2
$\begingroup$

How about:

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.

$\endgroup$
2
$\begingroup$

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}
$\endgroup$
1
$\begingroup$

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}

$\endgroup$
1
$\begingroup$

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