Performing Basic Linear Algebra Calculations with NumPy (Inverse Matrix, Determinant, Rank)

By using NumPy’s numpy.linalg module, you can easily calculate important linear algebra metrics such as inverse matrices and determinants.

Here, I will explain how to use the main linear algebra functions, along with basic operations like transposition and trace.

目次

1. List of Main Linear Algebra Functions

Below are representative functions included in the numpy.linalg module and their return values.

FunctionReturn Value Description
np.linalg.inv(M)Inverse Matrix
A matrix that becomes the identity matrix when multiplied by the original matrix. An error occurs if the matrix is not non-singular (determinant is 0).
np.linalg.det(M)Determinant
A value representing the “volume expansion rate” of the matrix. If this is 0, the matrix has no inverse.
np.linalg.matrix_rank(M)Rank
The number of linearly independent rows (or columns) in the matrix.

2. Executable Sample Code

The following code defines a 2×2 square matrix [[1, 2], [3, 4]] and performs various calculations.

The values are set to make the results of the inverse matrix and determinant easy to verify.

import numpy as np

def linear_algebra_demo():
    # 1. Define Matrix
    # Using [[1, 2], [3, 4]] as an example
    target_matrix = np.array([
        [1, 2],
        [3, 4]
    ])

    print("--- 元の行列 ---")
    print(target_matrix)

    # 2. Transpose Matrix (Transpose)
    # Swaps rows and columns. Use the .T attribute
    print("\n--- 転置行列 (.T) ---")
    print(target_matrix.T)

    # 3. Trace (Trace)
    # Sum of diagonal elements (1 + 4 = 5)
    print("\n--- トレース (.trace()) ---")
    print(target_matrix.trace())

    # 4. Inverse Matrix (Inverse Matrix)
    # Use np.linalg.inv()
    print("\n--- 逆行列 (np.linalg.inv) ---")
    try:
        inv_matrix = np.linalg.inv(target_matrix)
        print(inv_matrix)
    except np.linalg.LinAlgError:
        print("逆行列を計算できません(特異行列です)。")

    # 5. Determinant (Determinant)
    # Use np.linalg.det()
    # Formula: (1 * 4) - (2 * 3) = 4 - 6 = -2
    print("\n--- 行列式 (np.linalg.det) ---")
    det_val = np.linalg.det(target_matrix)
    print(f"{det_val:.2f}")

    # 6. Rank (Rank)
    # Use np.linalg.matrix_rank()
    # Since rows are independent, the rank will be 2
    print("\n--- ランク (np.linalg.matrix_rank) ---")
    rank_val = np.linalg.matrix_rank(target_matrix)
    print(rank_val)

if __name__ == "__main__":
    linear_algebra_demo()

Explanation: Distinguishing Methods and Functions

Used as Array Attributes/Methods

  • Transpose: variable_name.T
  • Trace (Sum of diagonal elements): variable_name.trace()

These have low computational cost, and the array object itself possesses these features.

Used via np.linalg Module

  • Inverse Matrix: np.linalg.inv(variable_name)
  • Determinant: np.linalg.det(variable_name)
  • Rank: np.linalg.matrix_rank(variable_name)

These require complex processing, so they are provided as functions within the dedicated linalg (Linear Algebra) module.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次