首页 > 解决方案 > How to add a constant value to every element of a Numpy array but the diagonal elements?

问题描述

I need to finish defining the function below.

def add_val_to_non_diag(A, val):
    pass

Here is what I want to happen:

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

add_val_to_non_diag(A, 1)

Output

[[1, 3, 4],
 [5, 5, 7],
 [8, 9, 9]]

标签: pythonnumpy

解决方案


您可以将值添加到每个元素,然后从对角线中减去。

import numpy as np

def add_val_to_non_diag(A, v):
    return A + v * (1 - np.eye(A.shape[0]))

A = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
add_val_to_non_diag(A, 1)
=> array([[1., 3., 4.],
          [5., 5., 7.],
          [8., 9., 9.]])

推荐阅读