HEADLESS_0NE - 27 days ago 16
Python Question

# Creating an identity Matrix containing diagonally determined values

Essentially, I'm looking for an efficient piece of code to generate the following matrix:

``````[[1 2 3 4 5]
[2 3 4 5 6]
[3 4 5 6 7]
[4 5 6 7 8]
[5 6 7 8 9]]
``````

I came up with the following, which works, but it's not particularly pretty, and I was thinking there's probably a way to really utilize
`numpy`
for this (beyond just creating the matrix and pretty-printing it):

``````import copy
import numpy as np

identity_count = 5
priority_matrix = np.identity(identity_count, dtype=int)

rating_start = 1
maximum_rating = identity_count * 2
rating_range = range(rating_start, maximum_rating)

priority_copy = copy.copy(priority_matrix)

for row_idx, row in enumerate(priority_copy):
rating_pos = 0
for col_idx, item in enumerate(row):
priority_matrix[row_idx][col_idx] = rating_range[rating_pos]
rating_pos += 1
rating_start += 1
rating_range = range(rating_start, maximum_rating)

print(np.matrix(priority_matrix))
``````

There has to be a more efficient way of doing this (doesn't need to be with
`numpy`
).

Thank you!

You can achieve this in a simple one-liner with a list comprehension. I'm afraid that I don't know a `numpy`-specific way of doing this, but you could always convert to an array afterwards.
`matrix = [[x for x in range(y,y+5)] for y in range(1,6)]`