Take a unitary matrix U
. I want to swap the columns such that the largest element of each column (in absolute value) is on the diagonal (modulo ties). What is the best way to do this in numpy?
Maybe you can try the example below (but as I said in the comment, you cannot always guarantee all of the max absolute values by columns could be arranged along the diagonal).
import numpy as np
np.random.seed(0)
# Create a unitary matrix U
M = np.random.rand(3,3)
U, _ = np.linalg.qr(M)
# Find the indices of the largest element in each column (in absolute value)
largest_indices = np.argmax(np.abs(U), axis=0)
# Sort the indices based on the values in descending order
sorted_indices = np.argsort(largest_indices)
# Reorder the columns of U based on the sorted indices
U_out = U[:, sorted_indices]
print(f'U = \n {U}')
print(f'U_out = \n {U_out}')
and you will see
U =
[[-0.617629 0.02482174 -0.7860778 ]
[-0.61320586 -0.64104698 0.46155968]
[-0.49245609 0.76710015 0.41115004]]
U_out =
[[-0.617629 -0.7860778 0.02482174]
[-0.61320586 0.46155968 -0.64104698]
[-0.49245609 0.41115004 0.76710015]]
and you could verify the unitary property of U
by
print(f'U@U.T = \n {U@U.T}')
which shows
U@U.T =
[[1.00000000e+00 1.13938611e-16 1.20208703e-16]
[1.13938611e-16 1.00000000e+00 7.53666611e-17]
[1.20208703e-16 7.53666611e-17 1.00000000e+00]]