Search code examples
pythonnumpymatrixcomparison

Create new matrices from the comparison of two matrices


I have two matrices X1 and X2 representing the complex solution of a polynom:

X1=(N.t[:,1,1]-N.t[:,0,0]-np.sqrt(delta))/2*(N.t[:,1,0])
X2=(N.t[:,1,1]-N.t[:,0,0]+np.sqrt(delta))/2*(N.t[:,1,0])

I'm trying to create two new matrices C1 and C2: C1 must contains the maximum values: max(X1, X2) and C2 must contains the minimum values: min(X1, X2). I used np.abs to compare the values since they are complex but I don't know how to make the indexation.

May someone could help me please?


Solution

  • To compare complexe numbers, you first need to "convert" them to real ones using their absolute values :

    X1_real, X2_real  = np.abs(X1), np.abs(X2)
    

    Then, you can simply use numpy's where function, as follows :

    boolean_array = (X1_real >= X2_real) # Or >, as you want.
    
    C1 = np.where(boolean_array, X1, X2) # If X1_real[i] is >= X2_real[i], then C1[i] will be equal to X1[i], otherwise to X2[i].
    C2 = np.where(boolean_array, X2, X1) # The opposite here.
    

    This matches the maximum and minimum arrays you seek !