7
$\begingroup$

How can I get a function that gives the following output?

listX = {a, b, c, d}
numberX = 3
myDuplicatesList[listX, numberX] 

{{a,a,a},{b,b,b},{c,c,c},{d,d,d}}

$\endgroup$
1

8 Answers 8

10
$\begingroup$

I like using KroneckerProduct for problems like this:

KroneckerProduct[listX, ConstantArray[1, numberX]]

{{a, a, a}, {b, b, b}, {c, c, c}, {d, d, d}}

The KroneckerProduct approach should be much faster than the others for large vectors.

$\endgroup$
8
$\begingroup$

Alternatively:

listX = {a, b, c};
numberX = 3;
Table[ConstantArray[i, numberX], {i, listX}]

{{a, a, a}, { b, b, b}, {c, c, c}}

Or:

listX = {a, b, c, d};
numberX = 3;

Transpose@Table[i, {numberX}, {i, listX}]
$\endgroup$
2
  • 1
    $\begingroup$ Or ConstantArray[#, numberX] & /@ listX $\endgroup$
    – Bob Hanlon
    Commented Mar 8, 2019 at 16:57
  • 1
    $\begingroup$ No need to use Transpose, just invert the order of the arguments: Table[i, {i,listX}, numberX] $\endgroup$
    – jjagmath
    Commented Mar 9, 2019 at 12:18
5
$\begingroup$

Array:

Array[listX &, numberX, 1, Transpose[{##}] &]

{{a, a, a}, {b, b, b}, {c, c, c}, {d, d, d}}

ArrayPad:

ArrayPad[List /@ listX, {0, {0, numberX - 1}}, "Fixed"]

{{a, a, a}, {b, b, b}, {c, c, c}, {d, d, d}}

PadRight:

PadRight[{#}, numberX, "Fixed"] & /@ listX  )* or *)
PadRight[List /@ listX, {Automatic, numberX}, "Fixed"]

{{a, a, a}, {b, b, b}, {c, c, c}, {d, d, d}}

TensorProduct:

TensorProduct[listX, Array[1 &, numberX]]

{{a, a, a}, {b, b, b}, {c, c, c}, {d, d, d}}

ArrayResample:

ArrayResample[listX, Scaled @ numberX , "Bin", Resampling -> "NearestLeft"]

{a, a, a, b, b, b, c, c, c, d, d, d}

Partition[%, numberX]

{{a, a, a}, {b, b, b}, {c, c, c}, {d, d, d}}

$\endgroup$
4
$\begingroup$

one way might be

listX    = {a, b, c, d}
numberX  = 3
Transpose[{listX}].{Table[1, {numberX}]}

Mathematica graphics

$\endgroup$
4
$\begingroup$
Transpose@ConstantArray[listX, numberX]

{{a, a, a}, {b, b, b}, {c, c, c}, {d, d, d}}

$\endgroup$
3
$\begingroup$

Yet Another Way:

Flatten[ConstantArray[{listX}, numberX], {2, 3}]

And another (the last argument 1 is necessary only when listX is not a flat list):

Outer[Times, listX, ConstantArray[1, numberX], 1]
$\endgroup$
2
$\begingroup$
Transpose[{listX}[[ConstantArray[1, numberX]]]]
$\endgroup$
1
$\begingroup$
listX = {a, b, c, d};
numberX = 3;

Using SequenceReplace:

SequenceReplace[listX, {g_} :> Table[g, numberX]]

Using Replace:

listX // Replace[#, a_ :> Table[a, numberX], {1}] &

{{a, a, a}, {b, b, b}, {c, c, c}, {d, d, d}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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