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?

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
Mencia
  • 1,324
  • 12
  • 26

6 Answers6

10

How about this?

Quotient[Range[6], 3, 1] + 1
   {1, 1, 1, 2, 2, 2}
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
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}
bill s
  • 68,936
  • 4
  • 101
  • 191
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}
bill s
  • 68,936
  • 4
  • 101
  • 191
2

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.

partial81
  • 3,101
  • 1
  • 23
  • 30
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}

DavidC
  • 16,724
  • 1
  • 42
  • 94
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]]]
Aky
  • 2,719
  • 12
  • 19