I have a function that outputs a matrix in a new basis. However, depending on the size of the matrix the number of basis matrix differ. So in simplified "Matlab pseudo code":
if matrixsize==1
for a1=1:4
out(a1)=Matrix*basis(a1)
end
elseif matrixsize==2
for a1=1:4
for a2=a1:4
out(a1,a2)=Matrix*basis(a1)*basis(a2)
end
end
elseif matrixsize==3
for a1=1:4
for a2=a1:4
for a3=a2:4
out(a1,a2,a3)=Matrix*basis(a1)*basis(a2)*basis(a3)
end
end
end
elseif ...
and so on
Is it possible to write this code, for any value of matrix size? In other words: Is it possible to create a loop that automatically creates the loops above? If this does not work in Matlab, is there maybe a solution in Python?
(Background: This question comes from quantum physics, where I want to write a quantum state in the Pauli basis)
Here is a working Matlab code that shows the problem:
function T=newbasis(n)
%create a random matrix
m=2^n;
M=randn(m);
%Pauli matrices
s{1}=sparse([1,0;0,1]);
s{2}=sparse([0,1;1,0]);
s{3}=sparse([0,-1i;1i,0]);
s{4}=sparse([1,0;0,-1]);
if n==1
for a1=1:4
T(a1)=trace(M*betterkron(s{a1}));
end
elseif n==2
for a1=1:4
for a2=a1:4
T(a1,a2)=trace(M*betterkron(s{a1},s{a2}));
end
end
elseif n==3
for a1=1:4
for a2=a1:4
for a3=a2:4
T(a1,a2,a3)=trace(M*betterkron(s{a1},s{a2},s{a3}));
end
end
end
else
T=[]
end
%Not very clever but just to keep it simple
function krn=betterkron(A,varargin)
krn = A;
for j = 2:nargin;
krn = kron(krn,varargin{j-1});
end
end
end
shas to be sparse? Pauli matrices are rather small ...