简体   繁体   English

Python 中的矩阵运算

[英]Matrix operations in Python

I want to write a function so that it takes a Matrix, a row number and a column number.我想写一个 function 以便它需要一个矩阵、一个行号和一个列号。 And thereafter to get the matrix such that 1 in the A(i,j) position and zeros in all the other positions in the i-th column using only row operations.此后仅使用行操作获得矩阵,使得 A(i,j) position 中的 1 和第 i 列中所有其他位置的零。 I am new to Python.我是 Python 的新手。 Please give me some help.请给我一些帮助。 Thank you.谢谢你。

How I started is as this,我是如何开始的,

import numpy as np

def A = np.array([B]) # the matrix B is yet to provide def A = np.array([B]) # 矩阵 B 尚未提供

def i = A[i,:]

def j= A[:,j]

But this doesn't seems to be working!但这似乎不起作用!

` `

import numpy as np

m = np.array([[1, 1, 1, 1],[2, 2, 2, 2],[3, 3, 3, 3]])


def func(matrix, col, row):
    matrix[:, col] = 0
    matrix[row, col] = 1


func(m, 1, 1)

print(m)`

hope it helps:)希望能帮助到你:)

Setup:设置:

import numpy as np          
from functools import reduce

N = 6
A = np.random.randint(0,10,(N,N))
i,j = np.random.randint(0,N,2)
A
# array([[8, 9, 8, 1, 9, 4],
#        [0, 3, 5, 4, 5, 2],
#        [2, 7, 4, 6, 2, 7],
#        [9, 8, 1, 5, 1, 9],
#        [0, 1, 0, 8, 0, 3],
#        [3, 4, 5, 0, 6, 7]])
i,j
# (5, 1)

Helpers:帮手:

I = np.identity(N)                    
e = I[:,None]      # standard base row vectors                   
eT = I[...,None]   # standard base column vectors                                             

The row ops:行操作:

rowops = [I + eT[i]@e[i]*(1/A[i,j]-1)] + [I - (eT[k]*A[k,j])@(e[i]/A[i,j]) for k in range(6) if k!=i]                          

The first one scales the ith row.第一个缩放第 i 行。 The others subtract the ith row times a factor from the kth row.其他人从第 k 行中减去第 i 行乘以一个因子。

Let's apply them one by one and keep track of the jth column:让我们一一应用它们并跟踪第 j 列:

B = A.copy()                       
for r in reversed(rowops):
    print(B[:,j])
    B = r@B
# [9 3 7 8 1 4]
# [9. 3. 7. 8. 0. 4.]
# [9. 3. 7. 0. 0. 4.]
# [9. 3. 0. 0. 0. 4.]
# [9. 0. 0. 0. 0. 4.]
# [0. 0. 0. 0. 0. 4.]
print(B[:,j])
# [0. 0. 0. 0. 0. 1.]

Now let's combine all rowops into a single op by multiplying them:现在让我们通过将所有 rowop 相乘来将它们组合成一个 op:

combined = reduce(np.matmul,rowops)

This gives indeed the same result when applied to A当应用于A时,这确实给出了相同的结果

np.allclose(combined@A,B)
# True

This combined op we could have obtained directly:我们可以直接获得这个组合操作:

R = I + (eT[i]-A@eT[j])@e[i]/A[i,j]

Check:查看:

np.allclose(combined,R)
# True

Applied to A:适用于 A:

R@A
# array([[  1.25,   0.  ,  -3.25,   1.  ,  -4.5 , -11.75],
#        [ -2.25,   0.  ,   1.25,   4.  ,   0.5 ,  -3.25],
#        [ -3.25,   0.  ,  -4.75,   6.  ,  -8.5 ,  -5.25],
#        [  3.  ,   0.  ,  -9.  ,   5.  , -11.  ,  -5.  ],
#        [ -0.75,   0.  ,  -1.25,   8.  ,  -1.5 ,   1.25],
#        [  0.75,   1.  ,   1.25,   0.  ,   1.5 ,   1.75]])

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

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