[英]Vectors and Matrices from the NumPy Module
In python, how to write program that create two 4 * 4 matrices A and B whose elements are random numbers.在python中,如何编写程序创建两个元素为随机数的4 * 4矩阵A和B。 Then create a matrix C that looks like
然后创建一个矩阵 C 看起来像
C = ⎡A B⎤
⎣B A⎦
Find the diagonal of the matrix C. The diagonal elements are to be presented in a 4 * 2 matrix.找到矩阵 C 的对角线。对角线元素将呈现在 4 * 2 矩阵中。
import numpy as np
matrix_A = np.random.randint(10, size=(4, 4))
matrix_B = np.random.randint(10, size=(4, 4))
matrix_C = np.array([[matrix_A, matrix_B], [matrix_B, matrix_A]])
d= matrix_C.diagonal()
D=d.reshape(2,4)
print(f'This is matrix C:\n{matrix_C}')
print(f'These are the diagonals of Matrix C:\n{D}')
The construction那个工程
matrix_C = np.array([[matrix_A, matrix_B], [matrix_B, matrix_A]])
does not concatenate matrices, but creates 4th order tensor (put matrices inside matrix).不连接矩阵,而是创建四阶张量(将矩阵放在矩阵中)。 You can check that by
您可以通过以下方式检查
print(matrix_C.shape) # (2, 2, 4, 4)
To lay out blocks call np.block
, then all other parts of your code should work fine:要布置块调用
np.block
,那么代码的所有其他部分都应该可以正常工作:
matrix_C = np.block([[matrix_A, matrix_B], [matrix_B, matrix_A]])
print(matrix_C.shape) # (8, 8)
d= matrix_C.diagonal()
D=d.reshape(2,4) # np.array([matrix_A.diagonal(), matrix_A.diagonal()])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.