-1

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!

John
  • 3
  • 2
  • 2
    Have you considered using `numpy.diag`? – mkrieger1 May 17 '21 at 15:01
  • What is the shape of the resulting matrix supposed to be? – mkrieger1 May 17 '21 at 15:02
  • Please always think about showing real output, that is so easier to understand ;) – azro May 17 '21 at 15:02
  • 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. – John May 17 '21 at 16:04
  • 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] – John May 17 '21 at 16:07

1 Answers1

0

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.

gboffi
  • 22,939
  • 8
  • 54
  • 85