Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    
Quotient does the job! –  Ali May 27 '13 at 15:28
    
Since everybody's going nuts with alternative solutions: one could also use Fold[]+Riffle[] for the task... –  J. M. May 28 '13 at 4:16
add comment

6 Answers 6

up vote 10 down vote accepted

How about this?

Quotient[Range[6], 3, 1] + 1
   {1, 1, 1, 2, 2, 2}
share|improve this answer
    
Precisely, thanks @J.M you are genius, holly smokes!!:) –  Mencia May 27 '13 at 15:34
    
how do you give format to the question? –  Mencia May 27 '13 at 15:41
    
See this for stuff on formatting. –  J. M. May 27 '13 at 15:43
add comment

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}
share|improve this answer
add comment

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.

share|improve this answer
add comment

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}
share|improve this answer
add comment

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}

share|improve this answer
add comment

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]]]
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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