Search code examples
pythonarraysnumpydiagonal

How to build a diagonal matrix in python?


I have matrix a which has the shape of [100,100], and matrix b of the same shape [100,100]. They are filled with some values.

What I want to do, is to build such diagonal matrixes [[a1,0],[0,b1]] for each element of a and b.

What is the best to do this?

I belive the expected shape is then array c = [2,2,100,100], where first [2,2] represent the shape of one diagonal matrix, and in total, there are [100,100] of such arrays.

F.e. let's suppose my a = [[1,2],[3,4]], b = [[5,6],[7,8]] . What I wanna get: arr1 = [[1,0],[0,5]], array2 = [[2,0],[0,6]], and so on.. so, in total the final shape is [2,2,4,4]

Thank you!


Solution

  • You wrote that the final shape of your "matrix of diagonal matrices" should be (2, 2, n, n) but IMO what you really want is a (n, n, 2, 2) shape, so that you can address it using out[i,j] to obtain

    [ [a[i,j],  0],
      [0,  b[i,j]] ]
    

    With your possible agreement on my different understanding, here it is the code that gives yo what you want

    In [64]: import numpy as np
        ...: n = 3 ; nn = n*n
        ...: a, b = np.arange(2*nn).reshape(2,n,n)
        ...: c = np.transpose(np.array((a,b)),(1,2,0)).reshape(n,n,2)
        ...: out = np.zeros((n,n,2,2))
        ...: out[:,:,0,0] = c[:,:,0]; out[:,:,1,1] = c[:,:,1]
        ...: print('2,1',a[2,1],b[2,1],out[2,1],sep='\n')
        ...: print('0,0',a[0,0],b[0,0],out[0,0],sep='\n')
        ...: print('0,2',a[0,2],b[0,2],out[0,2],sep='\n')
    2,1
    7
    16
    [[ 7.  0.]
     [ 0. 16.]]
    0,0
    0
    9
    [[0. 0.]
     [0. 9.]]
    0,2
    2
    11
    [[ 2.  0.]
     [ 0. 11.]]
    
    In [65]: out.shape
    Out[65]: (3, 3, 2, 2)
    

    It should be possible to generalize this procedure to an arbitrary number of rectangular N×M matrices a, b, c, ..., n, ... with a little more of brain consumption.