2
$\begingroup$

First I will start with the code involving KroneckerProduct that I want to replicate. So we have

Nx = 2;
Nz = 1;
zas = {3, 2}; (*Nz+1 length vector*)
zzas = Flatten@ConstantArray[zas, Nx+1]

giving

{3, 2, 3, 2, 3, 2}

and

mat = {{q, w, e},{r, t, y},{u, i, o}};

(An Nx+1 by Nx+1 matrix)

Then

(zzas*KroneckerProduct[mat,IdentityMatrix[Nz+1]]) // MatrixForm

produces

{{3 q, 0, 3 w, 0, 3 e, 0}, {0, 2 q, 0, 2 w, 0, 2 e}, {3 r, 0, 3 t, 0, 
  3 y, 0}, {0, 2 r, 0, 2 t, 0, 2 y}, {3 u, 0, 3 i, 0, 3 o, 0}, {0, 
  2 u, 0, 2 i, 0, 2 o}}

or as an image

enter image description here

Now, I want to be able to replicate this result using only zas and mat. The result of the KroneckerProduct operation basically multiplies the matrix mat by each entry in zas - which can be replicated with

ceco=Table[zas[[ii]]*mat, {ii, 1, Nz+1}];

and then arranges them in a certain way. So, if

am=ceco[[1]]
bm=ceco[[2]]

then the matrix that results from the KroneckerProduct can be created for example as

{Append[Riffle[am[[1]], 0], 0], 
 Reverse[Append[Riffle[Reverse[bm[[1]]], 0], 0]], 
 Append[Riffle[am[[2]], 0], 0], 
 Reverse[Append[Riffle[Reverse[bm[[2]]], 0], 0]], 
 Append[Riffle[am[[3]], 0], 0], 
 Reverse[Append[Riffle[Reverse[bm[[3]]], 0], 0]]}

Now, I did that by hand, but I want an automatic way of doing it for any Nx and Nz. I am also open to any other approaches of achieving the same. I basically want something that will be faster than working with the KroneckerProduct version, as for large matrices and vectors it becomes very slow.

$\endgroup$
2
$\begingroup$

With your definitions of zzas, mat, and Nz, this gives the desired form:

zzas (Outer[Times, mat, IdentityMatrix[Nz + 1]] // ArrayFlatten)
| improve this answer | |
$\endgroup$
  • $\begingroup$ I accept it as an answer as it does what I am asking for. I was hoping it would lead to a performance gain, but it doesn't seem to $\endgroup$ – ThunderBiggi Jan 28 '18 at 12:16
1
$\begingroup$
ArrayFlatten[TensorProduct[mat, zas IdentityMatrix[Nz + 1]]] // MatrixForm // TeXForm

$\left( \begin{array}{cccccc} 3 q & 0 & 3 w & 0 & 3 e & 0 \\ 0 & 2 q & 0 & 2 w & 0 & 2 e \\ 3 r & 0 & 3 t & 0 & 3 y & 0 \\ 0 & 2 r & 0 & 2 t & 0 & 2 y \\ 3 u & 0 & 3 i & 0 & 3 o & 0 \\ 0 & 2 u & 0 & 2 i & 0 & 2 o \\ \end{array} \right)$

| improve this answer | |
$\endgroup$
  • $\begingroup$ This seems to be slower in computing than the other solution $\endgroup$ – ThunderBiggi Jan 28 '18 at 12:15

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.