Python – マトリックス

Python – マトリックス

ここでは、このチュートリアル内で Python を使用して行列を形成するさまざまな方法について説明します。また、行列に対して実行できるさまざまな操作についても説明します。また、行列を形成するための外部モジュール Numpy と Python でのその操作についても説明します。

Python の行列

マトリックスとは何ですか?

行列は、行と列の長方形の配列に配置された数値の集合です。工学、物理学、統計、グラフィックスの分野では、行列は画像の回転やその他の種類の変換を表現するために広く使用されています。
この行列は m 行 n 列の行列と呼ばれ、次の記号で示されます。 m×n m 行 n 列がある場合。

Python を使用して単純な行列を作成する

方法 1: リストのリストを使用して行列を作成する

ここでは、リストのリストを使用して行列を作成します。

Python3




matrix> => [[> 1> ,> 2> ,> 3> ,> 4> ],> > [> 5> ,> 6> ,> 7> ,> 8> ],> > [> 9> ,> 10> ,> 11> ,> 12> ]]> print> (> 'Matrix ='> , matrix)>

出力:

Matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 

方法 2: Python でユーザーから行列入力を取得する

ここでは、ユーザーから多数の行と列を取得し、行列を出力します。

Python3




Row> => int> (> input> (> 'Enter the number of rows:'> ))> Column> => int> (> input> (> 'Enter the number of columns:'> ))> # Initialize matrix> matrix> => []> print> (> 'Enter the entries row wise:'> )> # For user input> # A for loop for row entries> for> row> in> range> (Row):> > a> => []> > # A for loop for column entries> > for> column> in> range> (Column):> > a.append(> int> (> input> ()))> > matrix.append(a)> # For printing the matrix> for> row> in> range> (Row):> > for> column> in> range> (Column):> > print> (matrix[row][column], end> => ' '> )> > print> ()>

出力:

Enter the number of rows:2 Enter the number of columns:2 Enter the entries row wise: 5 6 7 8 5 6 7 8 

時間計算量: O(n*n)
補助スペース: O(n*n)

方法 3: リスト内包表記を使用して行列を作成する

リスト内包表記は、Python でリストを定義および作成するための洗練された方法です。4 行 4 列を出力するために range 関数を使用しています。

Python3




matrix> => [[column> for> column> in> range> (> 4> )]> for> row> in> range> (> 4> )]> print> (matrix)>

出力:

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

マトリックスに値を割り当てる

方法 1: マトリックスの個々のセルに値を割り当てる

ここでは、行列内の個々のセル (1 行 1 列 = 11) に値を置換して割り当てています。

Python3




X> => [[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ], [> 7> ,> 8> ,> 9> ]]> row> => column> => 1> X[row][column]> => 11> print> (X)>

出力:

[[1, 2, 3], [4, 11 , 6], [7, 8, 9]] 

方法 2: マトリックスで負のインデックスを使用して個々のセルに値を割り当てる

ここでは、行列内の個々のセル (-2 行、-1 列 = 21) に値を置換して割り当てています。

Python3




row> => -> 2> column> => -> 1> X[row][column]> => 21> print> (X)>

出力:

[[1, 2, 3], [4, 5, 21 ], [7, 8, 9]] 

マトリックスの値へのアクセス

方法 1: 行列値にアクセスする

ここでは、行と列を渡すことによって行列の要素にアクセスしています。

Python3




print> (> 'Matrix at 1 row and 3 column='> , X[> 0> ][> 2> ])> print> (> 'Matrix at 3 row and 3 column='> , X[> 2> ][> 2> ])>

出力:

Matrix at 1 row and 3 column= 3 Matrix at 3 row and 3 column= 9 

方法 2: 負のインデックスを使用して行列値にアクセスする

ここでは、負のインデックスの行と列を渡すことによって行列の要素にアクセスしています。

Python3




import> numpy as np> X> => [[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ], [> 7> ,> 8> ,> 9> ]]> print> (X[> -> 1> ][> -> 2> ])>

出力:

8 

Python での行列の数学的演算

例 1: Python の for ループを使用して行列に値を追加する

ここでは、Python の for ループを使用して 2 つの行列を追加しています。

Python3




# Program to add two matrices using nested loop> X> => [[> 1> ,> 2> ,> 3> ],[> 4> ,> 5> ,> 6> ], [> 7> ,> 8> ,> 9> ]]> Y> => [[> 9> ,> 8> ,> 7> ], [> 6> ,> 5> ,> 4> ], [> 3> ,> 2> ,> 1> ]]> result> => [[> 0> ,> 0> ,> 0> ], [> 0> ,> 0> ,> 0> ], [> 0> ,> 0> ,> 0> ]]> # iterate through rows> for> row> in> range> (> len> (X)):> > # iterate through columns> > for> column> in> range> (> len> (X[> 0> ])):> > result[row][column]> => X[row][column]> +> Y[row][column]> for> r> in> result:> > print> (r)>

出力:

[10, 10, 10] [10, 10, 10] [10, 10, 10] 

時間計算量: O(n*n)
補助スペース: O(n*n)

例 2: リスト内包表記を使用した行列への値の加算と減算

リスト内包表記を使用した基本的な加算と減算の実行。

Python3




Add_result> => [[X[row][column]> +> Y[row][column]> > for> column> in> range> (> len> (X[> 0> ]))]> > for> row> in> range> (> len> (X))]> Sub_result> => [[X[row][column]> -> Y[row][column]> > for> column> in> range> (> len> (X[> 0> ]))]> > for> row> in> range> (> len> (X))]> print> (> 'Matrix Addition'> )> for> r> in> Add_result:> > print> (r)> print> (> ' Matrix Subtraction'> )> for> r> in> Sub_result:> > print> (r)>

出力:

Matrix Addition [10, 10, 10] [10, 10, 10] [10, 10, 10] Matrix Subtraction [-8, -6, -4] [-2, 0, 2] [4, 6, 8] 

時間計算量: O(n*n)
補助スペース: O(n*n)

例 3: 2 つの行列を乗算およ​​び除算する Python プログラム

Python ループを使用して基本的な乗算と除算を実行します。

Python3




rmatrix> => [[> 0> ,> 0> ,> 0> ], [> 0> ,> 0> ,> 0> ], [> 0> ,> 0> ,> 0> ]]> for> row> in> range> (> len> (X)):> > for> column> in> range> (> len> (X[> 0> ])):> > rmatrix[row][column]> => X[row][column]> *> Y[row][column]> > print> (> 'Matrix Multiplication'> ,)> for> r> in> rmatrix:> > print> (r)> > for> i> in> range> (> len> (X)):> > for> j> in> range> (> len> (X[> 0> ])):> > rmatrix[row][column]> => X[row][column]> /> /> Y[row][column]> print> (> ' Matrix Division'> ,)> for> r> in> rmatrix:> > print> (r)>

出力:

Matrix Multiplication [9, 16, 21] [24, 25, 24] [21, 16, 9] Matrix Division [0, 0, 0] [0, 1, 1] [2, 4, 9] 

時間計算量: O(n*n)
補助スペース: O(n*n)

行列で転置する

例: ループを使用して行列を転置する Python プログラム

行列の転置は、行を列に、列を行に変更することで得られます。つまり、A[][] の転置は、A[i][j] を A[j][i] に変更することで得られます。

Python3




X> => [[> 9> ,> 8> ,> 7> ], [> 6> ,> 5> ,> 4> ], [> 3> ,> 2> ,> 1> ]]> result> => [[> 0> ,> 0> ,> 0> ], [> 0> ,> 0> ,> 0> ], [> 0> ,> 0> ,> 0> ]]> # iterate through rows> for> row> in> range> (> len> (X)):> > # iterate through columns> > for> column> in> range> (> len> (X[> 0> ])):> > result[column][row]> => X[row][column]> for> r> in> result:> > print> (r)> > # # Python Program to Transpose a Matrix using the list comprehension> # rez = [[X[column][row] for column in range(len(X))]> # for row in range(len(X[0]))]> # for row in rez:> # print(row)>

出力:

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

時間計算量: O(n*n)
補助スペース: O(n*n)

Numpyを使った行列

Numpyを使用して行列を作成する

ここでは、numpy.random を使用して Numpy 配列を作成しています。 ランダムモジュール

Python3




import> numpy as np> > # 1st argument -->0 から 9 までの数字、>>

出力:

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

Numpy を使用した Python での行列数学演算

ここでは、Numpy を使用した加減算、乗算、除算などのさまざまな数学演算を取り上げます。

Python3




# initializing matrices> x> => numpy.array([[> 1> ,> 2> ], [> 4> ,> 5> ]])> y> => numpy.array([[> 7> ,> 8> ], [> 9> ,> 10> ]])> # using add() to add matrices> print> (> 'The element wise addition of matrix is : '> )> print> (numpy.add(x,y))> # using subtract() to subtract matrices> print> (> 'The element wise subtraction of matrix is : '> )> print> (numpy.subtract(x,y))> print> (> 'The element wise multiplication of matrix is : '> )> print> (numpy.multiply(x,y))> # using divide() to divide matrices> print> (> 'The element wise division of matrix is : '> )> print> (numpy.divide(x,y))>

出力:

The element wise addition of matrix is : [[ 8 10] [13 15]] The element wise subtraction of matrix is : [[-6 -6] [-5 -5]] The element wise multiplication of matrix is : [[ 7 16] [36 50]] The element wise division of matrix is : [[0.14285714 0.25 ] [0.44444444 0.5 ]] 

行列の内積と外積

ここでは、Python で NumPy を使用して行列とベクトルの内積、外積、外積を求めます。

Python3




X> => [[> 1> ,> 2> ,> 3> ],[> 4> ,> 5> ,> 6> ],[> 7> ,> 8> ,> 9> ]]> Y> => [[> 9> ,> 8> ,> 7> ], [> 6> ,> 5> ,> 4> ],[> 3> ,> 2> ,> 1> ]]> dotproduct> => np.dot(X, Y)> print> (> 'Dot product of two array is:'> , dotproduct)> dotproduct> => np.cross(X, Y)> print> (> 'Cross product of two array is:'> , dotproduct)>

出力:

Dot product of two array is: [[ 30 24 18] [ 84 69 54] [138 114 90]] Cross product of two array is: [[-10 20 -10] [-10 20 -10] [-10 20 -10]] 

Numpyを使用したPythonでの行列転置

行列で転置演算を実行するには、 numpy.transpose() 方法。

Python3




matrix> => [[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ]]> print> (> ' '> , numpy.transpose(matrix))>

出力:

[[1 4][2 5][3 6]] 

を作成します 空の行列 Python で NumPy を使用する

を使用して空の配列を初期化する np.zeros()

Python3




a> => np.zeros([> 2> ,> 2> ], dtype> => int> )> print> (> ' Matrix of 2x2: '> , a)> c> => np.zeros([> 3> ,> 3> ])> print> (> ' Matrix of 3x3: '> , c)>

出力:

Matrix of 2x2: [[0 0] [0 0]] Matrix of 3x3: [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] 

スライス Numpyを使用した行列内

スライスとは、行列から特定の行と列を選択し、選択されていない要素をすべて削除して新しい行列を作成するプロセスです。最初の例では、行列全体を出力し、2 番目の例では、初期インデックスとして 2、最後のインデックスとして 3、インデックス ジャンプを 1 として渡します。インデックスを変更したばかりの次の出力でも同じものが使用されます。 2にジャンプします。

Python3




X> => np.array([[> 6> ,> 8> ,> 10> ],> > [> 9> ,> -> 12> ,> 15> ],> > [> 12> ,> 16> ,> 20> ],> > [> 15> ,> -> 20> ,> 25> ]])> # Example of slicing> # Syntax: Lst[ Initial: End: IndexJump ]> print> (X[:])> print> (> ' Slicing Third Row-Second Column: '> , X[> 2> :> 3> ,> 1> ])> print> (> ' Slicing Third Row-Third Column: '> , X[> 2> :> 3> ,> 2> ])>

出力:

[[ 6 8 10] [ 9 -12 15] [ 12 16 20] [ 15 -20 25]] Slicing Third Row-Second Column: [16] Slicing Third Row-Third Column: [20] 

Numpyを使用して行と列を削除する

ここでは、np.delete() 関数を使用して行を削除しようとしています。コードでは、最初に 0 を削除しようとしました。 番目 行、次に 2 を削除しようとしました nd 行、そして 3 rd 行。

Python3




# create an array with integers> # with 3 rows and 4 columns> a> => np.array([[> 6> ,> 8> ,> 10> ],> > [> 9> ,> -> 12> ,> 15> ],> > [> 12> ,> 16> ,> 20> ],> > [> 15> ,> -> 20> ,> 25> ]])> # delete 0 th row> data> => np.delete(a,> 0> ,> 0> )> print> (> 'data after 0 th row deleted: '> , data)> # delete 1 st row> data> => np.delete(a,> 1> ,> 0> )> print> (> ' data after 1 st row deleted: '> , data)> # delete 2 nd row> data> => np.delete(a,> 2> ,> 0> )> print> (> ' data after 2 nd row deleted: '> , data)>

出力:

data after 0 th row deleted: [[ 9 -12 15] [ 12 16 20] [ 15 -20 25]] data after 1 st row deleted: [[ 6 8 10] [ 12 16 20] [ 15 -20 25]] data after 2 nd row deleted: [[ 6 8 10] [ 9 -12 15] [ 15 -20 25]] 

Numpy 配列に行/列を追加する

4 番目に列を 1 つ追加しました。 番目 np.hstack を使用して位置を指定します。

Python3




ini_array> => np.array([[> 6> ,> 8> ,> 10> ],> > [> 9> ,> -> 12> ,> 15> ],> > [> 15> ,> -> 20> ,> 25> ]])> # Array to be added as column> column_to_be_added> => np.array([> 1> ,> 2> ,> 3> ])> # Adding column to numpy array> result> => np.hstack((ini_array, np.atleast_2d(column_to_be_added).T))> # printing result> print> (> ' resultant array '> ,> str> (result))>

出力:

resultant array [[ 6 8 10 1] [ 9 -12 15 2] [ 15 -20 25 3]]