5
$\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$
6
$\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$
  • 1
    $\begingroup$ Or ConstantArray[#, numberX] & /@ listX $\endgroup$ – Bob Hanlon Mar 8 at 16:57
  • 1
    $\begingroup$ No need to use Transpose, just invert the order of the arguments: Table[i, {i,listX}, numberX] $\endgroup$ – jjagmath Mar 9 at 12:18
5
$\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$
3
$\begingroup$

one way might be

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

Mathematica graphics

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

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

$\endgroup$
2
$\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$
1
$\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$
0
$\begingroup$
Transpose[{listX}[[ConstantArray[1, numberX]]]]
$\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.