简体   繁体   English

在Python中创建2D矩阵列表

[英]Creating list of 2D matrices in Python

I am trying to create a list of 2d matrices, as per the illustration below: 我正在尝试创建二维矩阵列表,如下图所示:

list of 2d matrices 二维矩阵列表

Basically, I want to start with a NxN matrix with all zeros and sequentially replace the 0's with 1's (as shown in the image). 基本上,我想从一个全零的NxN矩阵开始,然后将0依次替换为1(如图所示)。 With each modification changing the 0's to 1's, I would like to output the matrix at that step and save it in a list or array. 每次修改将0更改为1时,我想在该步骤输出矩阵并将其保存在列表或数组中。

For the first row of matrices in the illustration, I have this: 对于图中的第一行矩阵,我有以下内容:

    dim = 4
    x=[]
    for i in range(0,dim):
        matrix = np.zeros((dim,dim))
        matrix[0,i] = 1
        x.append(matrix)
    m0 = x[0]
    m1 = x[0]+x[1]
    m2 = x[0]+x[1]+x[2]
    m3 = x[0]+x[1]+x[2]+x[3]

I would like to generalize this so I not only get the first row but the rest of the rows shown in the image and change the matrix size through 'dim'. 我想对此进行概括,以便不仅获得第一行,而且获得图像中显示的其余行,并通过“ dim”更改矩阵大小。 I can't seem to figure this out. 我似乎无法弄清楚。 I'd appreciate any help with this. 我将不胜感激。

This will do the job: 这将完成工作:

import numpy as np
dim = 4
x=[]
for i in range(dim):
    lst=[]
    matrix=np.zeros((dim,dim))
    vec=np.ones(i+1)
    for j in range(dim):
        matrix[0:i+1,j]=vec
        lst.append(np.copy(matrix))
    x.append(lst)
print(x)

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

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