- 用矩阵乘法的形式增加行向量
A
=
[
1
2
3
4
5
6
7
8
9
]
;
v
=
[
888
444
666
]
→
E
=
[
1
2
3
4
5
6
7
8
9
888
444
666
]
;
\begin{equation} A = \begin{bmatrix} 1&2&3\\\\ 4&5&6\\\\ 7&8&9\end{bmatrix};v=\begin{bmatrix} 888&444&666 \end{bmatrix}\to E=\begin{bmatrix} 1&2&3\\\\ 4&5&6\\\\ 7&8&9\\\\ 888&444&666\end{bmatrix}; \end{equation}
A=
147258369
;v=[888444666]→E=
147888258444369666
;
- 代码:
import numpy as np
np.set_printoptions(suppress=True, precision=3)
class MatrixAddVector(object):
def __init__(self, in_matrix, in_vector):
self.in_matrix = in_matrix
self.row, self.column = np.shape(self.in_matrix)
self.in_vector = in_vector
self.result = np.zeros((self.row + 1, self.column))
def add_vector(self):
my_vector = self.in_vector
my_matrix = self.in_matrix
my_row_1 = self.row + 1
my_column = self.column
left_ones = np.ones(my_row_1)
left_ones_diag = np.diag(left_ones)
left_matrix = left_ones_diag[:, :-1]
left_matrix_1 = left_matrix @ self.in_matrix
zeros_vector = np.zeros(my_row_1)
zeros_vector[-1] = 1
add_matrix = np.outer(zeros_vector, self.in_vector)
result = add_matrix + left_matrix_1
print(f"matrix=\n{self.in_matrix}")
print(f"vector={self.in_vector}")
print(f"result=\n{result}")
if __name__ == "__main__":
run_code = 0
new_matrix = np.arange(9).reshape(3, 3)+1
new_vector = np.array([888, 444, 666])
new_test = MatrixAddVector(new_matrix, new_vector)
new_test.add_vector()
matrix=
[[1 2 3]
[4 5 6]
[7 8 9]]
vector=[888 444 666]
result=
[[ 1. 2. 3.]
[ 4. 5. 6.]
[ 7. 8. 9.]
[888. 444. 666.]]