简体   繁体   English

如何在 python 中构建对角矩阵?

[英]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].我有形状为 [100,100] 的矩阵a和形状相同的矩阵b [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.我想要做的是为 a 和 b 的每个元素构建这样的对角矩阵 [[a1,0],[0,b1]]。

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.我相信预期的形状是数组 c = [2,2,100,100],其中第一个 [2,2] 表示一个对角矩阵的形状,总共有 [100,100] 个这样的 arrays。

Fe let's suppose my a = [[1,2],[3,4]], b = [[5,6],[7,8]]. Fe 假设我的 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]我想要得到:arr1 = [[1,0],[0,5]], array2 = [[2,0],[0,6]] 等等.. 所以,最终的形状是[2,2,4,4]

Thank you!谢谢!

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您写道,“对角矩阵矩阵”的最终形状应该是(2, 2, n, n)但 IMO 您真正想要的是(n, n, 2, 2)形状,以便您可以解决它使用out[i,j]获得

[ [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.应该可以将这个过程推广到任意数量的 N×M 矩形矩阵a, b, c, ..., n, ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM