Python – Matrix

Python – Matrix

Tukaj bomo razpravljali o različnih načinih, kako lahko oblikujemo matriko z uporabo Pythona, znotraj te vadnice pa bomo razpravljali tudi o različnih operacijah, ki jih je mogoče izvesti na matriki. obravnavali bomo tudi zunanji modul Numpy za oblikovanje matrike in njene operacije v Pythonu.

Matrix v Pythonu

Kaj je matrica?

Matrika je zbirka števil, razporejenih v pravokotni niz v vrsticah in stolpcih. Na področjih inženirstva, fizike, statistike in grafike se matrike pogosto uporabljajo za izražanje vrtenja slik in drugih vrst transformacij.
Matrika se imenuje m krat n matrika, označena s simbolom m x n če je m vrstic in n stolpcev.

Ustvarjanje preproste matrike z uporabo Pythona

1. način: Ustvarjanje matrike s seznamom seznamov

Tukaj bomo ustvarili matriko z uporabo seznama seznamov.

Python3




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

Izhod:

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

2. način: Uporabite vnos Matrix v Python

Tukaj od uporabnika vzamemo številne vrstice in stolpce ter natisnemo matriko.

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> ()>

Izhod:

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 

Časovna zahtevnost: O(n*n)
Pomožni prostor: O(n*n)

3. način: Ustvarite matriko z razumevanjem seznama

Razumevanje seznama je eleganten način za definiranje in ustvarjanje seznama v Pythonu, uporabljamo funkcijo obsega za tiskanje 4 vrstic in 4 stolpcev.

Python3




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

Izhod:

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

Dodeljevanje vrednosti v matriki

1. način: dodelite vrednost posamezni celici v Matrixu

Tukaj zamenjamo in dodelimo vrednost posamezni celici (1 vrstica in 1 stolpec = 11) v matriki.

Python3




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

Izhod:

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

2. način: dodelite vrednost posamezni celici z uporabo negativnega indeksiranja v Matrixu

Tukaj zamenjamo in dodelimo vrednost posamezni celici (-2 vrstica in -1 stolpec = 21) v matriki.

Python3




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

Izhod:

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

Dostopanje do vrednosti v matriki

1. način: dostop do vrednosti matrike

Tukaj dostopamo do elementov matrike s posredovanjem njene vrstice in stolpca.

Python3




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

Izhod:

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

2. način: Dostop do vrednosti Matrix z uporabo negativnega indeksiranja

Tukaj dostopamo do elementov matrike tako, da njeni vrstici in stolpcu posredujemo negativno indeksiranje.

Python3




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

Izhod:

8 

Matematične operacije z matriko v Pythonu

Primer 1: Dodajanje vrednosti v matriko z zanko for v pythonu

Tukaj dodajamo dve matriki z zanko Python for.

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

Izhod:

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

Časovna zahtevnost: O(n*n)
Pomožni prostor: O(n*n)

Primer 2: Seštevanje in odštevanje vrednosti v matriko z razumevanjem seznama

Izvajanje osnovnega seštevanja in odštevanja z razumevanjem seznama.

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

Izhod:

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

Časovna zahtevnost: O(n*n)
Pomožni prostor: O(n*n)

Primer 3: program Python za množenje in deljenje dveh matrik

Izvajanje osnovnega množenja in deljenja z zanko 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)>

Izhod:

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

Časovna zahtevnost: O(n*n)
Pomožni prostor: O(n*n)

Transponiraj v matrico

Primer: program Python za prenos matrike z uporabo zanke

Prenos matrike dobimo tako, da spremenimo vrstice v stolpce in stolpce v vrstice. Z drugimi besedami, prenos A[][] dobimo s spremembo A[i][j] v 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)>

Izhod:

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

Časovna zahtevnost: O(n*n)
Pomožni prostor: O(n*n)

Matrix z uporabo Numpy

Ustvarite matriko s pomočjo Numpy

Tukaj ustvarjamo matriko Numpy z uporabo numpy.random in a naključni modul .

Python3




import> numpy as np> > # 1st argument -->številke od 0 do 9,> # 2nd argument, row = 3, col = 3> array> => np.random.randint(> 10> , size> => (> 3> ,> 3> ))> print> (array)>

Izhod:

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

Matrične matematične operacije v Pythonu z uporabo Numpyja

Tukaj pokrivamo različne matematične operacije, kot so seštevanje, odštevanje, množenje in deljenje z uporabo Numpyja.

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

Izhod:

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

Pikčasti in križni produkt z matriko

Tukaj bomo našli notranje, zunanje in navzkrižne produkte matrik in vektorjev z uporabo NumPy v Pythonu.

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

Izhod:

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

Prenos matrice v Python z uporabo Numpy

Za izvedbo operacije transponiranja v matriki lahko uporabimo numpy.transpose() metoda.

Python3




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

Izhod:

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

Ustvarite prazna matrika z NumPy v Pythonu

Inicializacija prazne matrike z uporabo 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)>

Izhod:

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

Rezanje v Matrixu z uporabo Numpyja

Rezanje je postopek izbire določenih vrstic in stolpcev iz matrike in nato ustvarjanja nove matrike z odstranitvijo vseh neizbranih elementov. V prvem primeru tiskamo celotno matriko, v drugem posredujemo 2 kot začetni indeks, 3 kot zadnji indeks in skok indeksa kot 1. Enako se uporabi pri naslednjem izpisu, pravkar smo spremenili indeks skoči na 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> ])>

Izhod:

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

Izbrišite vrstice in stolpce s programom Numpy

Tukaj poskušamo izbrisati vrstice s funkcijo np.delete(). V kodi smo najprej poskušali izbrisati 0 th vrstico, potem smo poskušali izbrisati 2 nd vrstico, nato pa 3 rd vrstica.

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

Izhod:

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

Dodajte vrstico/stolpce v matriko Numpy

Dodali smo še en stolpec pri 4 th položaj z uporabo 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))>

Izhod:

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