简体   繁体   中英

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. Then create a matrix C that looks like

C = ⎡A B⎤
    ⎣B A⎦

Find the diagonal of the matrix C. The diagonal elements are to be presented in a 4 * 2 matrix.

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:

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()])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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