Answer the question
In order to leave comments, you need to log in
How can code be optimized with the numpy library?
The vector x=1:3 is given. Create a matrix of the 3rd order, on the diagonals of which the elements of the vector would be. If the diagonal is shorter than size(x), then the filling starts at the 1st element of the vector x.
def replace(diagonal, matrix):
matrix[0][0] = diagonal[0]
try:
matrix[1][1] = diagonal[1]
except IndexError:
pass
try:
matrix[2][2] = diagonal[2]
except IndexError:
pass
return matrix
Answer the question
In order to leave comments, you need to log in
It seems that with this command you can
numpy.diag (v), where v is your vector.
Details can be found here
https://numpy.org/doc/stable/reference/generated/n...
Filling with the last three elements from the diagonal vector:
matrix[np.diag_indices_from(matrix)] = diagonal[-min(matrix.shape):]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question