How to turn diagonal elements of a python matrix into a list

Asked

Viewed 1,660 times

-1

I have the following matrix, for example:

matriz = [[1, 2, 3, 4, 5, 6],
          [7, 8, 9, 3, 8, 9],
          [4, 5, 2, 3, 4, 4],
          [2, 3, 4, 5, 3, 6],
          [4, 5, 3, 4, 5, 6]]

I would like to obtain only the elements of the main diagonal, such as:

A = [1, 8, 2, 5, 5]
  • Your question made no sense. Please read the [Ask] guide and rephrase it. If you’re new to the community, I recommend doing the [tour] as well.

  • Put an example of what you want to make clear, so you can’t understand

  • I tried to clarify the example

  • And how is your matrix defined in Python? Ask this in the question too.

  • But this in the question

  • @Alexandrecandidoteixeira is not. In the question there is a representation of the matrix, but it is not as you are defining it in Python. This may completely change the answer and so I will vote to close as unclear until there is such a correction.

  • It only makes sense to speak in main diagonal with square matrices, and its example is a 6x5 matrix.

Show 2 more comments

1 answer

5

Your question really isn’t very clear. If your matrix is a list of lists, the solution is the following:

matriz = [[1, 2, 3, 4, 5, 6],
           [7, 8, 9, 3, 8, 9],
           [4, 5, 2, 3, 4, 4],
           [2, 3, 4, 5, 3, 6],
           [4, 5, 3, 4, 5, 6]]

diag = []
for i in range(len(matriz)):
    for j in range(len(matriz[0])):
        if i == j:
            diag.append(matriz[i][j])

print(diag)

The exit is [1, 8, 2, 5, 5]

If your matrix is an array numpy (and if not, I recommend using this library) the solution is as follows:

import numpy as np
array = np.array(matriz)
np.diag(array)

And the exit is array([1, 8, 2, 5, 5])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.