V
V
Viktor Khavrin2021-02-28 14:49:33
Python
Viktor Khavrin, 2021-02-28 14:49:33

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

How else can you solve this problem without using loops? Maybe there is an easier way to solve it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan., 2021-02-28
@LaRN

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...

A
Andrey Dugin, 2021-03-02
@adugin

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 question

Ask a Question

731 491 924 answers to any question