简体   繁体   English

来自 NumPy 模块的向量和矩阵

[英]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.

相关问题 numpy:将向量数组转换为对称矩阵数组 - numpy: converting array of vectors to array of symmetric matrices Python-numpy-许多矩阵乘以许多向量 - python - numpy - many matrices multiplying many vectors 如何在 numpy 中获取矩阵向量的网格? - How to get meshgrid of vectors of matrices in numpy? 多维矩阵中向量的点积(python,numpy) - dot product of vectors in multidimentional matrices (python, numpy) 如果没有 NumPy,我应该如何将两个向量或矩阵相减? - How should I subtract two vectors or matrices from each other without NumPy? 行向量矩阵之间的python numpy欧几里德距离计算 - python numpy euclidean distance calculation between matrices of row vectors 如何在 Python 和 numpy arrays 中可视化/连接向量、矩阵和表示? - How to visualize/connect vectors, matrices and representations in Python and numpy arrays? 在 Numpy 中的矩阵列表和向量列表之间应用矩阵点 - Apply matrix dot between a list of matrices and a list of vectors in Numpy numpy - einsum 表示法:矩阵堆栈与向量堆栈的点积 - numpy - einsum notation: dot product of a stack of matrices with stack of vectors 将作为矩阵的numpy数组字段值拆分为列向量 - Splitting numpy array field values that are matrices into column vectors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM