I am having trouble of filling a square matrix of n x n with a list of the size m.
What I want to achieve is something like this:
arr = np.array([
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]], dtype=float)
And a list like this:
myList= [1, 2, 3, 4, 5, 6, 7]
The output should be:
arr = np.array([
[4, 5, 6, 7],
[3, 4, 5, 6],
[2, 3, 4, 5],
[1, 2, 3, 4]], dtype=float)
My function works, however I think this is not the most elegant way.
def fill_array(img, myList):
arr = np.ones(np.shape(img))
diag_size = (np.shape(img)[0] * 2) - 1
diag_idx = np.median(np.linspace(1, diag_size, diag_size))
# First iterate through the lower half, main diagonal and then upper half
i = 1
while i <= diag_size:
factor = myList[i - 1]
if i < diag_idx:
position = int(diag_idx - i)
np.fill_diagonal(arr[position:, :], factor)
elif i == diag_idx:
np.fill_diagonal(arr[0:, :], factor)
elif i > diag_idx:
position = int(i - diag_idx)
np.fill_diagonal(arr[:, position:], factor)
i += 1
return arr
Is there a better solution for that? Thanks in advance!