The following code takes a vector x of variable length, computes the outer product of the vector with itself to form the matrix $\rho$ of dimension $2^n \times 2^n$. The function T[i_, list_List] then computes elements of a tensor $\mathcal{T}$ of rank $n$ according to

$$T_{\mu_1,...,\mu_n}=\text{Tr}(\rho \;\; \sigma_{\mu_1}\otimes...\otimes\sigma_{\mu_n})$$

with $\mu_1,...,\mu_n=1,2,3$ and $\sigma_i$ being the three Pauli Matrices.

OuterVectorProduct[x_] := KroneckerProduct[x, x] 
T[i_, list_List] := 
 FullSimplify[Tr[i.KroneckerProduct @@ PauliMatrix[list]]] 

That is: T[rho,{1,1}]outputs the $T_{11}$ element of the Tensor $\mathcal T$ with respect to some matrix $\rho$.

I would now like to write a function that outputs the entire tensor. To do so, I need to extract the number of arguments within the list in the function T[i_,list_List].

That is, in our example T[rho,{1,1}], I need to extract the number of arguments in the curly braces.

How does one do that?



1 Answer 1


Probably not the most efficient way to do so, but for descently sized n, this should work well:

T[i_, list_List] := Tr[i.KroneckerProduct @@ PauliMatrix[list]]
n = 4;
ρ = RandomReal[{-1, 1}, 2^n];
A = ArrayReshape[
   T[ρ, #] & /@ Tuples[Range[3], n], 
   ConstantArray[3, n]
A // Dimensions

{3, 3, 3, 3}

  • $\begingroup$ Thanks for your answer! Unfortunately, I seem to get a $RecursionLimit error when running this code $\endgroup$
    – Pentaquark
    Aug 6, 2019 at 13:04
  • $\begingroup$ I'm sorry if I'm being dense here, but doesn't the fact that n is set to 4 define the length of the output string? Ideally, list_List should be an arbitary number of arguments, and the function returns the amount of arguments put into that list. $\endgroup$
    – Pentaquark
    Aug 6, 2019 at 13:15
  • 1
    $\begingroup$ The size of the output should actually only depend on ρ. So, if you write a function of ρ, you would set n = Log2[Length[ρ]] in the body of that function. $\endgroup$ Aug 6, 2019 at 13:22
  • $\begingroup$ Ah ok, gotcha. Thank you for your help! $\endgroup$
    – Pentaquark
    Aug 6, 2019 at 13:25
  • 1
    $\begingroup$ You're welcome! $\endgroup$ Aug 6, 2019 at 15:21

Your Answer

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

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