How to make a gradient line between two points in numpy array?

Viewed 48

I hope to generate a gradient line between two points in a numpy array. For example, if I have a numpy array like

[[1,0,0,0]
 [0,0,0,0]
 [0,0,0,0]
 [0,0,0,4]]

What I hope to get is find a line between the [0,0] and [3,3], and have a liner gradient. So I hope to make an array like

[[1,0,0,0]
 [0,2,0,0]
 [0,0,3,0]
 [0,0,0,4]]

The tricky part is the matrix may not be a perfect nxn. I don't care if some lines have two non-zero elements (because we cannot get a perfect diagonal for mxn matrix). The element of the same line can be the same in my case.

I am wondering is there an efficient way to make this happen?

1 Answers

You can use np.fill_diagonal:

np.fill_diagonal(arr, np.arange(arr[0,0], arr[-1,-1]+1))

Output:

array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])
Related