MATLAB: I have a problem interpreting reshape with a matrix product

linear algebramatrix multiplicationoperatorsreshape

Here is my code:
if true
%{
Pi = zeros(n^2,n^2);
Psi0 = zeros(n^2,1);
for k=1:n
aux = zeros(n,1);
aux(k) = 1;
psi{k} = kron(aux,sqrt(G(:,k)));
P{k} = psi{k} * psi{k}';
Pi = Pi + P{k};
Psi0 = Psi0 + psi{k};
end
Psi0 = 1/sqrt(n)*Psi0;
%construct the swap operator S
S = zeros(n^2,n^2);
for k=1:n
for j=1:n
S((k-1)*n+j,(j-1)*n+k) = 1;
end
end
% construct time evolution operator U:
U = S * (2*Pi - eye(n^2));
U2 = U^2;
%%Perform the actual iterative dynamics:
% # of double-steps of the quantum walk:
steps = 1000;
state = reshape(Psi0,n,n);
for k=1:steps
state = reshape(U2*state(:),n,n);
for j=1:n
p(k,j) = norm(state(j,:))^2;
end
end
} end
In the end where there's "state = reshape(U2*state(:),n,n);" I can't understand how this product can be possible.. U2 is an (n^2,n^2) matrix and state is now (n,n);
Can anyone explain me this?
Moreover I'm trying to translate this in Python in order to apply it to network analysis, but with Python the command reshape from numpy (which I suppose is similar to MATLAB reshape) doesn't work at all: it tells me "ValueError: shapes (n^2,n^2) and (n,n) not aligned: n^2 (dim 1) != n (dim 0)" ; in this sense it approves my suggestions!
I would be thankful if anyone can help me! Thanks a lot!!
Simone

Best Answer

Hello Simone,
state = reshape(Psi0,n,n); % Psi0 is n^2 x 1 column vector
% and state is n x n
for k=1:steps
state = reshape(U2*state(:),n,n); % state(:) is n^2 x 1 column vector.
% U2 is n^2 x n^2 matrix.
% their product is n^2 x 1 column vector.
% so reshape to n x n works.