In [53]: a = np.arange(25).reshape(5,5)
In [54]: a
Out[54]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
In [55]: mask = np.abs(np.add.outer(np.arange(5), -np.arange(5))) < 3
In [56]: mask
Out[56]:
array([[ True, True, True, False, False],
[ True, True, True, True, False],
[ True, True, True, True, True],
[False, True, True, True, True],
[False, False, True, True, True]], dtype=bool)
In [57]: a[mask] = 100
In [58]: a
Out[58]:
array([[100, 100, 100, 3, 4],
[100, 100, 100, 100, 9],
[100, 100, 100, 100, 100],
[ 15, 100, 100, 100, 100],
[ 20, 21, 100, 100, 100]])
Explanation: np.add.outer
can be used to make addition tables:
In [59]: np.add.outer(np.arange(5), np.arange(5))
Out[59]:
array([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
By changing the sign of one of the arange
s (and using np.abs
), you can measure the distance from the diagonal:
In [61]: np.abs(np.add.outer(np.arange(5), -np.arange(5)))
Out[61]:
array([[0, 1, 2, 3, 4],
[1, 0, 1, 2, 3],
[2, 1, 0, 1, 2],
[3, 2, 1, 0, 1],
[4, 3, 2, 1, 0]])
So you can "select" all elements that are a certain distance from the diagonal by writing a simple inequality:
In [62]: np.abs(np.add.outer(np.arange(5), -np.arange(5))) < 3
Out[62]:
array([[ True, True, True, False, False],
[ True, True, True, True, False],
[ True, True, True, True, True],
[False, True, True, True, True],
[False, False, True, True, True]], dtype=bool)
Once you have this boolean mask, you can assign new values to a
with
a[mask] = val
Thus, fill_banded
could look something like this:
import numpy as np
def fill_banded(a, val, width=1):
mask = np.abs(np.add.outer(np.arange(a.shape[0]), -np.arange(a.shape[1]))) < width
a[mask] = val
a = np.arange(30).reshape(6,5)
fill_banded(a, val=True, width=3)
print(a)