在python中组装矩阵(scipy / numpy)

时间:2021-07-09 21:19:15

I was wondering if there is an easy way to assemble matrices along the diagonal in python, adding values if they overlap. Here is a handy diagram I stole from the Matlab forum: https://i.stack.imgur.com/ZunrZ.jpg

我想知道是否有一种简单的方法在python中沿对角线组装矩阵,如果它们重叠则添加值。这是我从Matlab论坛上偷走的一个方便的图表:https://i.stack.imgur.com/ZunrZ.jpg

Currently, I am trying to implement it to work with a set number of 2x2 matrices, but the end goal is to make the code assemble an arbitrary amount of arbitrary sized matrices(all the same size ofc., max 4x4).

目前,我正在尝试实现它以使用一定数量的2x2矩阵,但最终目标是使代码组装任意数量的任意大小的矩阵(所有相同大小的c。,最大4x4)。

2 个解决方案

#1


3  

I'm not sure how to vectorize this, but you can do it fairly directly with setitem:

我不确定如何对此进行矢量化,但你可以直接用setitem做到:

k = k1 = np.array([[1,2],[3,4]])   # etc
ks = [k1, k2, k3, k4]
[n] = set(k.shape)
N = len(ks)
A = np.zeros((N+1, N+1))
for i, k in enumerate(ks):
    A[i:i+n, i:i+n] += k

#2


0  

First an example with two 2x2 matrices on a 5x5 big matrix:

首先在5x5大矩阵上有两个2x2矩阵的例子:

import numpy as np
M = np.zeros((5,5))
M1 = np.matrix([[1,2],[3,4]])
M2 = np.matrix([[1,2],[3,4]])
M[:2,:2] += M1
M[1:3, 1:3] += M2
M

yields

array([[ 1.,  2.,  0.,  0.,  0.],
   [ 3.,  5.,  2.,  0.,  0.],
   [ 0.,  3.,  4.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.]])

In general, if you have a KxK matrix of zeros M, and K-r+1 rxr matrices in some indexable, you can do

一般来说,如果你有一个零的Mx的KxK矩阵和一些可索引的K-r + 1 rxr矩阵,你可以做

for i in range(K-r+1): 
    M[i+r:i+r] += matrices[i]

#1


3  

I'm not sure how to vectorize this, but you can do it fairly directly with setitem:

我不确定如何对此进行矢量化,但你可以直接用setitem做到:

k = k1 = np.array([[1,2],[3,4]])   # etc
ks = [k1, k2, k3, k4]
[n] = set(k.shape)
N = len(ks)
A = np.zeros((N+1, N+1))
for i, k in enumerate(ks):
    A[i:i+n, i:i+n] += k

#2


0  

First an example with two 2x2 matrices on a 5x5 big matrix:

首先在5x5大矩阵上有两个2x2矩阵的例子:

import numpy as np
M = np.zeros((5,5))
M1 = np.matrix([[1,2],[3,4]])
M2 = np.matrix([[1,2],[3,4]])
M[:2,:2] += M1
M[1:3, 1:3] += M2
M

yields

array([[ 1.,  2.,  0.,  0.,  0.],
   [ 3.,  5.,  2.,  0.,  0.],
   [ 0.,  3.,  4.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.]])

In general, if you have a KxK matrix of zeros M, and K-r+1 rxr matrices in some indexable, you can do

一般来说,如果你有一个零的Mx的KxK矩阵和一些可索引的K-r + 1 rxr矩阵,你可以做

for i in range(K-r+1): 
    M[i+r:i+r] += matrices[i]