I'm trying to write a function (A) which calls another function (B) (in my case KroneckerProduct) where the number and the position of the arguments of function (B) depend on the arguments of function (A).

Here an example of what I mean:

I have two matrices (1 and 2) and I want to do the KroneckerProduct of them n times (in the example n=5) where in position a and b (in the example 1 and 3) I have matrix2, in all the other (2,4,5) I have matrix1.

matrix1 = IdentityMatrix[2];
matrix2 = {{2,2},{2,2}};

function[1, 3, 5] = KronekerProduct[
    matrix2, matrix1, matrix2, matrix1, matrix1

I can think several ways of doing that but none of them is elegant or short, while I think there is a compact way of doing it and I can't see it/


  • $\begingroup$ is it always be about matrix1 and matrix2? Don't you want them as a part of the input. Is it always be about matrix2 being in exactly two spots? If not, please elaborate on what do you want to be able to input in general. $\endgroup$
    – Kuba
    Commented Jun 14, 2017 at 20:12
  • $\begingroup$ Thank you for your answer. What I need is just three matrices (matrix 1, 2 and 3) where 2 of them are in position p1 and p2, but I asked just for two matrices for making the example simpler since the generalisation from 2 to 3 is straightforward: in this sense, jjc385 answer works nicely for what I need! $\endgroup$
    – Fraccalo
    Commented Jun 15, 2017 at 6:37

1 Answer 1


How about

function[p1_, p2_, n_, mat1_:matrix1, mat2_:matrix2] :=
 KroneckerProduct @@ (
   ConstantArray[mat1, n]
     // ReplacePart[p1|p2 -> mat2]

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.