Как найти главную диагональ в матрице питон

Время чтения 3 мин.

Функция np.diag() определена в библиотеке numpy, которую можно импортировать как import numpy as np. Мы можем создавать многомерные массивы и получать другую математическую статистику с помощью numpy. Имя функции Python diag() происходит от diagonal.

Содержание

  1. Что такое функция np.diag() в Python?
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Примеры программ для метода diag() в Python
  6. Пример 1
  7. Пример 2
  8. Создание массива и построение диагонали
  9. Построение диагонали из массива NumPy
  10. Заключение

Функция np.diag() извлекает и создает диагональный массив на Python. Она принимает массив и k в качестве параметров и возвращает диагональный массив из заданного массива.

Синтаксис

Параметры

Функция принимает два параметра, один из которых является необязательным.

  • Первый параметр — это входной массив, представленный arr.
  • Второй параметр — k, является необязательным и по умолчанию принимает значение 0. Если значение этого параметра больше 0, это означает, что диагональ находится выше главной диагонали, и наоборот, если нет.

Возвращаемое значение

Возвращает массив с диагональным массивом.

Примеры программ для метода diag() в Python

Напишем программу, показывающую работу функции diag() в Python.

Пример 1

# app.py

import numpy as np

a = np.matrix([[1, 2, 3], [4, 5, 6], [9, 8, 7]])

print(“Main Diagonal: n”, np.diag(a), “n”)

print(“Above main diagonal: n”, np.diag(a, 1),

      “n”)  # k=1(for above main diagonal)

print(“Below main diagonal: n”, np.diag(a, 1))  # k=-1(for below main diagonal)

Выход

Main Diagonal: [1 5 7]

Above main diagonal: [2 6]

Below main diagonal: [4 8]

В этом примере мы используем numpy diag() и можем видеть, что, передавая разные значения k, можем получить их диагональные элементы. Здесь мы увидели главную диагональ в матрице, затем диагональ выше главной диагонали при передаче значения k=1 и наоборот при передаче значения k=-1.

Пример 2

Напишем программу, которая берет матрицу 4×4 и применяет функцию diag().

См. следующий код.

# app.py

import numpy as np

a = np.matrix([[1, 2, 3], [4, 5, 6], [9, 8, 7], [11, 13, 15]])

print(“Main Diagonal: n”, np.diag(a), “n”)

# k=1(for above main diagonal)

print(“Above main diagonal: n”, np.diag(a, 1), “n”)

#k=-1(for below main diagonal)

print(“Below main diagonal: n”, np.diag(a, 1))

Выход

python3 app.py

Main Diagonal:

[1 5 7]

Above main diagonal:

[2 6]

Below main diagonal:

[ 4  8 15]

В этом примере мы передали матрицу 4 × 4 и получили требуемый результат главной диагонали, выше главной диагонали (k = 1) и ниже главной диагонали (k = -1).

Создание массива и построение диагонали

См. следующий код.

import numpy as np

data = np.arange(12).reshape((4,3))

print(data)

dignl = np.diag(data, k=0)

print(‘The diagonal is: ‘)

print(dignl)

Выход

python3 app.py

[[ 0  1  2]

[ 3  4  5]

[ 6  7  8]

[ 9 10 11]]

The diagonal is:

[0 4 8]

В этом примере мы взяли k = 0. Это главная диагональ, которая состоит из

  • 0
  • 4
  • 8

Если мы возьмем k = 1, он вернет [1, 5]. См. следующий код.

# app.py

import numpy as np

data = np.arange(12).reshape((4,3))

print(data)

dignl = np.diag(data, k=1)

print(‘The diagonal is: ‘)

print(dignl)

Выход

python3 app.py

[[ 0  1  2]

[ 3  4  5]

[ 6  7  8]

[ 9 10 11]]

The diagonal is:

[1 5]

Если мы возьмем k = -1, это даст нам нижнюю диагональ главной диагонали.

См. следующий код.

import numpy as np

data = np.arange(12).reshape((4, 3))

print(data)

dignl = np.diag(data, k=1)

print(‘The diagonal is: ‘)

print(dignl)

Выход

python3 app.py

[[ 0  1  2]

[ 3  4  5]

[ 6  7  8]

[ 9 10 11]]

The diagonal is:

[ 3  7 11]

Главная диагональ нашего массива — [0, 4, 8], а нижняя диагональ — [3, 7, 11]. Вот почему, когда мы устанавливаем k=-1, он вернет [3, 7, 11]. Если вы передадите k = -2, то он вернет [6, 10]

Построение диагонали из массива NumPy

Если вы хотите создать диагональ из массива, вы можете использовать метод np diag().

# app.py

import numpy as np

a = np.array([1, 2, 3, 4])

print(a)

d = np.diag(a)

print(‘The diagonal is: ‘)

print(d)

Выход

python3 app.py

[1 2 3 4]

The diagonal is:

[[1 0 0 0]

[0 2 0 0]

[0 0 3 0]

[0 0 0 4]]

Если у вас есть вектор-строка, вы можете сделать следующее.

# app.py

import numpy as np

a = np.array([[1, 2, 3, 4]])

print(a)

d = np.diag(a[0])

print(‘The diagonal is: ‘)

print(d)

Выход

python3 app.py

[[1 2 3 4]]

The diagonal is:

[[1 0 0 0]

[0 2 0 0]

[0 0 3 0]

[0 0 0 4]]

Заключение

Функция Python numpy.diagonal() используется для извлечения диагонали и записи в полученный массив; возвращает она копию или представление, зависит от того, какую версию numpy вы используете.

In python, we have seen many functions or methods of the numpy library. In this tutorial, we will be learning about the numpy diag() function. As we come in a situation where we need to calculate the diagonal, print the diagonal of an array of matrices. We will see all the ways through which we can print the values of the diagonal through the numpy diag() function.

What is Numpy Diag() function?

The diag() function is used to extract and construct a diagonal 2-d array with a numpy library. It contains two parameters: an input array and k, which decides the diagonal, i.e., main diagonal, lowe diagonal, or the upper diagonal. It is the numpy library function, which is used to perform the mathematical and statistics operation on the multidimensional array.

Syntax

numpy.diag(arr,k=0) 

Parameters

  • arr: It is an input array. If it is a 2-D array, it returns a copy of its k-th diagonal. If it is a 1-D array, it returns a 2-D array with arr on the kth diagonal.
  • k: It is an integer value and an optional input. If k>0, then the diagonal is above the main diagonal, and if k<0, then the diagonal is below the main diagonal. By default, it is 0.

Return value

It returns the extracted diagonal or a constructed diagonal.

Examples of numpy diag() function

Let us understand the numpy diag() function of the numpy module in details with the help of examples:

1. Finding diagonal without k parameter

In this example, we will create a multidimensional array(matrix) with the help of numpy and then apply the numpy diag() function without passing the k parameter. By default, it is set to 0 and also called as main diagonal. Let us look at the example for understanding the concept in detail.

#import numpy library
import numpy as np

a = np.matrix([[1, 2, 3], [4, 5, 6], [9, 8, 7]])

print("Main diagonal : ",np.diag(a))

Output:

Main diagonal :  [1 5 7]

Explanation:

  • Firstly, we will be importing the numpy library with an alias name as np.
  • Then, we will take the input for creating a multidimensional array.
  • After that, we will apply the numpy diag() without the value of the k parameter. By default, it is set to 0.
  • At last, we have printed the main diagonal of the multidimensional array.
  • Hence, you can see the output.

2. Printing upper diagonal of main diagonal

In this example, we will be printing the upper diagonal of the main diagonal in the multidimensional array. In this, we will pass the k parameter with the positive value of k to give us the upper diagonal. By applying the numpy diag() function, we will print the upper diagonal. Let us look at the example for understanding the concept in detail.

#import numpy library
import numpy as np

a = np.matrix([[1, 2, 3], [4, 5, 6], [9, 8, 7]])

print(a)
print("Main diagonal : ",np.diag(a,1))

Output:

[[1 2 3]
 [4 5 6]
 [9 8 7]]
Main diagonal :  [2 6]

Explanation:

  • Firstly, we will be importing the numpy library with an alias name as np.
  • Then, we will take the input for creating a multidimensional array.
  • After that, we will apply the numpy diag() with the k parameter value equal to 1.
  • For the upper diagonal, we need to put the k value as positive and greater than 0.
  • At last, we have printed the upper diagonal of the main diagonal of the multidimensional array.
  • Hence, you can see the output.

3. Printing lower diagonal of main diagonal

In this example, we will be printing the lower diagonal of the main diagonal in the multidimensional array. In this, we will pass the k parameter with the negative value of k to give us the lower diagonal. By applying the numpy diag() function, we will print the lower diagonal. Let us look at the example for understanding the concept in detail.

#import numpy library
import numpy as np

a = np.matrix([[1, 2, 3], [4, 5, 6], [9, 8, 7]])

print(a)
print("Main diagonal : ",np.diag(a,-1))

Output:

[[1 2 3]
 [4 5 6]
 [9 8 7]]
Main diagonal :  [4 8]

Explanation:

  • Firstly, we will be importing the numpy library with an alias name as np.
  • Then, we will take the input for creating a multidimensional array.
  • After that, we will apply the numpy diag() with the k parameter value equal to 1.
  • For the lower diagonal, we need to put the k value as negative and lesser than 0.
  • At last, we have printed the lower diagonal of the main diagonal of the multidimensional array.
  • Hence, you can see the output.

4. Using arange function to create an array and then construct the diagonal

In this example, we will be importing the numpy library. Then, we will use arange() from numpy to create the multidimensional array. After that, we will print the main diagonal of the array created. Let us look at the example for understanding the concept in detail.

#import numpy library
import numpy as np

x = np.arange(9).reshape((3,3))

print(x)
print("Main diagonal : ",np.diag(x))

Output:

[[0 1 2]
 [3 4 5]
 [6 7 8]]
Main diagonal :  [0 4 8]

Explanation:

  • Firstly, we will be importing the numpy library with an alias name as np.
  • Then, we will apply the np.arange() function from the numpy library to create a multidimensional array.
  • After that, we have printed the matrix formed.
  • At last, we have applied the diag() function and printed the diagonal of the array.
  • Hence, you can see the output.

5. Constructing diagonal from array

In this example, we will be importing the numpy library. Then, we will be passing the array values in the numpy array() function. Finally, we will apply the numpy diag function to create the diagonal of the values passed inside the array. This will construct a diagonal array. Let us look at the example for understanding the concept in detail.

#importing numpy library
import numpy as np

a = np.array([5, 6, 7, 8])

print(a)
print("Diagonal : ",np.diag(a))

Output:

[5 6 7 8]
Diagonal : 
  [[5 0 0 0]
 [0 6 0 0]
 [0 0 7 0]
 [0 0 0 8]]

Explanation:

  • Firstly, we will be importing the numpy library with an alias name as np.
  • Then, we have created an array with the help of the numpy library.
  • After that, we have printed the array, which we have taken as an input.
  • Finally, we have applied the numpy diag() function for constructing the diagonal for the array values and print the output.
  • Hence, you can see the output.

What is numpy diagonal() of a 3-D array?

The numpy diagonal() function is used to extract and construct a diagonal of a 2-d and 3-d array with a numpy library.

Let us take an example and understand the concept in detail.

#import numpy library
import numpy as np

a = np.arange(8).reshape(2,2,2);
print(a)
print("n")
print(" diagonal output : ",a.diagonal(0,0,1))

Output:

[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]


diagonal output :  [[0 6]
 [1 7]]

Explanation:

  • Firstly, we will be importing the numpy library with an alias name as np.
  • Then, we will apply the np.arange() function from the numpy library to create a 3-d multidimensional array.
  • Then, we will print the 3-d array.
  • After that, we will apply the diagonal() function with all the parameters and print the output.
  • Hence, you can see the output.

Difference between numpy diag() and numpy diagonal() ?

Numpy diag()

The diag() function is used to extract and construct a diagonal 2-d array with a numpy library.

Numpy diagonal()

The diagonal() function is used to extract and construct a diagonal of a 2-d and 3-d array with a numpy library.

Example of numpy diag() and numpy diagonal()

In this example, we will explain the examples of the numpy diag() function operating on the 2-d array and numpy diagonal() function operating on the 2-d and 3-d array both. We will understand the difference between in a more efficient way through this example.

#import numpy library
import numpy as np

x = np.arange(9).reshape((3,3))

print(x)
print("n")
print("2-d Main diagonal : ",np.diag(x))
print("n")

#numpy diagonal() example
import numpy as np

#2-d array
x = np.arange(9).reshape((3,3))
print("2-d Main diagonal : ",np.diagonal(x))

#3-d array
a = np.arange(8).reshape(2,2,2);
print(a)
print("n")
print(" 3-d diagonal output : ",a.diagonal(0,0,1))

Output:

[[0 1 2]
 [3 4 5]
 [6 7 8]]


2-d Main diagonal :  [0 4 8]


2-d Main diagonal :  [0 4 8]
[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]


 3-d diagonal output :  [[0 6]
 [1 7]]

Explanation:

  • Firstly, we will be importing the numpy library with an alias name as np.
  • Then, we will apply the np.arange() function from the numpy library to create a 2-d multidimensional array.
  • After that, we have printed the matrix formed.
  • At last, we have applied the diag() function and printed the diagonal of the array.
  • Hence, you can see the output.

Conclusion

In this tutorial, we have learned about the concept of the numpy diagonal() function. We have seen how to print the diagonal of the multidimensional array and also construct a multidimensional diagonal. We have all the ways through which we can do so and all the examples are explained in detail for a better understanding of the concept. You can use any of the methods according to your need in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

numpy.diagonal(a, offset=0, axis1=0, axis2=1)[source]#

Return specified diagonals.

If a is 2-D, returns the diagonal of a with the given offset,
i.e., the collection of elements of the form a[i, i+offset]. If
a has more than two dimensions, then the axes specified by axis1
and axis2 are used to determine the 2-D sub-array whose diagonal is
returned. The shape of the resulting array can be determined by
removing axis1 and axis2 and appending an index to the right equal
to the size of the resulting diagonals.

In versions of NumPy prior to 1.7, this function always returned a new,
independent array containing a copy of the values in the diagonal.

In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
but depending on this fact is deprecated. Writing to the resulting
array continues to work as it used to, but a FutureWarning is issued.

Starting in NumPy 1.9 it returns a read-only view on the original array.
Attempting to write to the resulting array will produce an error.

In some future release, it will return a read/write view and writing to
the returned array will alter your original array. The returned array
will have the same type as the input array.

If you don’t write to the array returned by this function, then you can
just ignore all of the above.

If you depend on the current behavior, then we suggest copying the
returned array explicitly, i.e., use np.diagonal(a).copy() instead
of just np.diagonal(a). This will work with both past and future
versions of NumPy.

Parameters:
aarray_like

Array from which the diagonals are taken.

offsetint, optional

Offset of the diagonal from the main diagonal. Can be positive or
negative. Defaults to main diagonal (0).

axis1int, optional

Axis to be used as the first axis of the 2-D sub-arrays from which
the diagonals should be taken. Defaults to first axis (0).

axis2int, optional

Axis to be used as the second axis of the 2-D sub-arrays from
which the diagonals should be taken. Defaults to second axis (1).

Returns:
array_of_diagonalsndarray

If a is 2-D, then a 1-D array containing the diagonal and of the
same type as a is returned unless a is a matrix, in which case
a 1-D array rather than a (2-D) matrix is returned in order to
maintain backward compatibility.

If a.ndim > 2, then the dimensions specified by axis1 and axis2
are removed, and a new axis inserted at the end corresponding to the
diagonal.

Raises:
ValueError

If the dimension of a is less than 2.

See also

diag

MATLAB work-a-like for 1-D and 2-D arrays.

diagflat

Create diagonal arrays.

trace

Sum along diagonals.

Examples

>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
       [2, 3]])
>>> a.diagonal()
array([0, 3])
>>> a.diagonal(1)
array([1])

A 3-D example:

>>> a = np.arange(8).reshape(2,2,2); a
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])
>>> a.diagonal(0,  # Main diagonals of two arrays created by skipping
...            0,  # across the outer(left)-most axis last and
...            1)  # the "middle" (row) axis first.
array([[0, 6],
       [1, 7]])

The sub-arrays whose main diagonals we just obtained; note that each
corresponds to fixing the right-most (column) axis, and that the
diagonals are “packed” in rows.

>>> a[:,:,0]  # main diagonal is [0 6]
array([[0, 2],
       [4, 6]])
>>> a[:,:,1]  # main diagonal is [1 7]
array([[1, 3],
       [5, 7]])

The anti-diagonal can be obtained by reversing the order of elements
using either numpy.flipud or numpy.fliplr.

>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.fliplr(a).diagonal()  # Horizontal flip
array([2, 4, 6])
>>> np.flipud(a).diagonal()  # Vertical flip
array([6, 4, 2])

Note that the order in which the diagonal is retrieved varies depending
on the flip function.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    With the help of Numpy matrix.diagonal() method, we are able to find a diagonal element from a given matrix and gives output as one dimensional matrix.

    Syntax : matrix.diagonal()

    Return : Return diagonal element of a matrix

    Example #1 :
    In this example we can see that with the help of matrix.diagonal() method we are able to find the elements in a diagonal of a matrix.

    import numpy as np

    gfg = np.matrix('[6, 2; 3, 4]')

    geeks = gfg.diagonal()

    print(geeks)

    Example #2 :

    import numpy as np

    gfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]')

    geeks = gfg.diagonal()

    print(geeks)

    Last Updated :
    12 Apr, 2019

    Like Article

    Save Article

    The Numpy library in Python comes with a number of useful functions to work with and manipulate the data in arrays. In this tutorial, we will look at how to create a diagonal matrix using Numpy with the help of some examples.

    create a diagonal matrix in numpy

    You can use the numpy built-in numpy.diag() function to create a diagonal matrix. Pass the 1d array of the diagonal elements.

    The following is the syntax –

    numpy.diag(v, k)

    To create a diagonal matrix you can use the following parameters –

    1. v – The 1d array containing the diagonal elements.
    2. k – The diagonal on which the passed elements (elements of the 1d array, v) are to be placed. By default, k is 0 which refers to the main diagonal. Diagonals above the main diagonal are positive and the ones below it are negative (see the examples below).

    It returns a 2d array with the passed elements placed on the kth diagonal.

    Examples

    Let’s now look at examples of using the above syntax to get create a diagonal matrix using the Numppy library.

    Example 1 – Diagonal matrix from 1d array placed on the default diagonal in Numpy

    Let’s now use the numpy.diag() function to create a diagonal matrix from a 1d array. For example, we’ll only pass the 1d array and use the default diagonal.

    import numpy as np
    
    # create a 1d array of diagonal elements
    ar = np.array([1, 2, 3])
    # create a diagonal matrix
    res = np.diag(ar)
    # display the returned matrix
    print(res)

    Output:

    [[1 0 0]
     [0 2 0]
     [0 0 3]]

    We get a 2d numpy array which is a diagonal matrix. All the elements in the matrix are zero except the diagonal elements. You can see that the passed elements are placed on the main diagonal (k=0).

    Example 2 – Diagonal matrix from 1d array placed on a custom diagonal in Numpy

    In the above example, we placed the elements from the 1d array of the main diagonal.

    The numpy.diag() function comes with an optional parameter, k that you can use to specify the diagonal you want to use to create the diagonal matrix.

    The below image better illustrates the different values of k (representing different diagonals) for a 3×3 matrix.

    diagonals of a 3x3 matrix in numpy

    k is 0 by default. The diagonals below the main diagonal have k < 0 and the diagonals above it have k > 0.

    Let’s now use the numpy.diag() function to create a diagonal matrix by placing the passed elements on the k=-1 diagonal.

    # create a 1d array of diagonal elements
    ar = np.array([1, 2, 3])
    # create a diagonal matrix with elements on digonal, k=-1
    res = np.diag(ar, k=-1)
    # display the returned matrix
    print(res)

    Output:

    [[0 0 0 0]
     [1 0 0 0]
     [0 2 0 0]
     [0 0 3 0]]

    The resulting diagonal matrix has the passed elements on the k = -1 diagonal. Here, the resulting matrix is 4×4 because all the elements in the passed array cannot be accommodated on the k=-1 diagonal of a 3×3 matrix, hence the added dimensions.

    Alternative usage of the numpy.diag() function

    In the above examples, we used the numpy.diag() function to create a diagonal matrix by passing a 1d array and placing its elements on the kth diagonal.

    You can also use the numpy.diag() function to extract the diagonal elements from a 2d array.

    For example, if you pass a 2d array to the numpy.diag() function, it will return its diagonal elements on the kth diagonal (which is 0 by default).

    # create a 2D numpy array
    arr = np.array([
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ])
    # get the diagonal elements
    res = np.diag(arr)
    # display the diagonal elements
    print(res)

    Output:

    [1 5 9]

    We get the elements on the main diagonal as a 1d array.

    Summary

    In this tutorial, we looked at how to create a diagonal matrix using a 1d array in Numpy. The following are the key takeaways from this tutorial.

    • Use the numpy.diag() function to create a diagonal matrix. Pass the diagonal elements as a 1d array.
    • You can specify the diagonal to place the elements in the passed array on using the optional parameter k. By default, it represents the main diagonal, k = 0.

    You might also be interested in –

    • Extract Diagonal Elements From Numpy Array
    • Numpy – Get the Lower Triangular Matrix (With Examples)
    • Get the First N Rows of a 2D Numpy Array
    • Numpy – Remove Duplicates From Array

    Subscribe to our newsletter for more informative guides and tutorials.
    We do not spam and you can opt out any time.

    • Piyush Raj

      Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

      View all posts

    Добавить комментарий