Aici vom discuta diferite moduri în care putem forma o matrice folosind Python în cadrul acestui tutorial, vom discuta și despre diferitele operații care pot fi efectuate pe o matrice. vom acoperi, de asemenea, modulul extern Numpy pentru a forma o matrice și operațiunile acesteia în Python.

Ce este matricea?
O matrice este o colecție de numere aranjate într-o matrice dreptunghiulară în rânduri și coloane. În domeniile ingineriei, fizicii, statisticii și graficii, matricele sunt utilizate pe scară largă pentru a exprima rotațiile imaginilor și alte tipuri de transformări.
Matricea este denumită o matrice m cu n, notată prin simbol m x n dacă sunt m rânduri și n coloane.
Crearea unei matrice simple folosind Python
Metoda 1: Crearea unei matrice cu o listă de listă
Aici, vom crea o matrice folosind lista de liste.
Python3
matrix> => [[> 1> ,> 2> ,> 3> ,> 4> ],> > [> 5> ,> 6> ,> 7> ,> 8> ],> > [> 9> ,> 10> ,> 11> ,> 12> ]]> print> (> 'Matrix ='> , matrix)> |
>
>
Ieșire:
Matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]>
Metoda 2: luați intrarea Matrix de la utilizator în Python
Aici, luăm un număr de rânduri și coloane de la utilizator și imprimăm Matricea.
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> ()> |
>
>
Ieșire:
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>
Complexitatea timpului: O(n*n)
Spațiu auxiliar: O(n*n)
Metoda 3: Creați o matrice folosind înțelegerea listei
Înțelegerea listelor este o modalitate elegantă de a defini și de a crea o listă în Python, utilizăm funcția de interval pentru imprimarea a 4 rânduri și 4 coloane.
Python3
matrix> => [[column> for> column> in> range> (> 4> )]> for> row> in> range> (> 4> )]> print> (matrix)> |
>
>
Ieșire:
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]>
Atribuirea unei valori într-o matrice
Metoda 1: Atribuiți valoare unei celule individuale în Matrix
Aici înlocuim și atribuim valoare unei celule individuale (1 rând și 1 coloană = 11) în Matrice.
Python3
X> => [[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ], [> 7> ,> 8> ,> 9> ]]> row> => column> => 1> X[row][column]> => 11> print> (X)> |
>
>
Ieșire:
[[1, 2, 3], [4, 11 , 6], [7, 8, 9]]>
Metoda 2: Atribuiți o valoare unei celule individuale folosind indexarea negativă în Matrix
Aici înlocuim și atribuim valoare unei celule individuale (-2 rând și -1 coloană = 21) din Matrice.
Python3
row> => -> 2> column> => -> 1> X[row][column]> => 21> print> (X)> |
>
>
Ieșire:
[[1, 2, 3], [4, 5, 21 ], [7, 8, 9]]>
Accesarea valorii într-o matrice
Metoda 1: Accesarea valorilor Matrix
Aici, accesăm elemente ale unei matrice trecându-i rândul și coloana.
Python3
print> (> 'Matrix at 1 row and 3 column='> , X[> 0> ][> 2> ])> print> (> 'Matrix at 3 row and 3 column='> , X[> 2> ][> 2> ])> |
>
>
Ieșire:
Matrix at 1 row and 3 column= 3 Matrix at 3 row and 3 column= 9>
Metoda 2: Accesarea valorilor Matrix folosind indexarea negativă
Aici, accesăm elemente ale unei matrice trecând rândul și coloana acesteia pe indexarea negativă.
Python3
import> numpy as np> X> => [[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ], [> 7> ,> 8> ,> 9> ]]> print> (X[> -> 1> ][> -> 2> ])> |
>
>
Ieșire:
8>
Operații matematice cu Matrix în Python
Exemplul 1: Adăugarea de valori la o matrice cu o buclă for în python
Aici, adăugăm două matrice folosind bucla for Python.
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)> |
>
>
Ieșire:
[10, 10, 10] [10, 10, 10] [10, 10, 10]>
Complexitatea timpului: O(n*n)
Spațiu auxiliar: O(n*n)
Exemplul 2: Adăugarea și scăderea valorilor la o matrice cu înțelegere a listei
Efectuarea adunării și scăderii de bază folosind înțelegerea listelor.
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)> |
>
>
Ieșire:
Matrix Addition [10, 10, 10] [10, 10, 10] [10, 10, 10] Matrix Subtraction [-8, -6, -4] [-2, 0, 2] [4, 6, 8]>
Complexitatea timpului: O(n*n)
Spațiu auxiliar: O(n*n)
Exemplul 3: program Python pentru a multiplica și împărți două matrice
Efectuarea înmulțirii și împărțirii de bază folosind bucla Python.
Python3
java localdate
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)> |
>
>
Ieșire:
Matrix Multiplication [9, 16, 21] [24, 25, 24] [21, 16, 9] Matrix Division [0, 0, 0] [0, 1, 1] [2, 4, 9]>
Complexitatea timpului: O(n*n)
Spațiu auxiliar: O(n*n)
Transpune în matrice
Exemplu: Programul Python pentru a transpune o matrice folosind bucla
Transpunerea unei matrice se obține prin schimbarea rândurilor în coloane și a coloanelor în rânduri. Cu alte cuvinte, transpunerea lui A[][] se obține prin schimbarea A[i][j] în 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)> |
>
>
Ieșire:
[9, 6, 3] [8, 5, 2] [7, 4, 1]>
Complexitatea timpului: O(n*n)
Spațiu auxiliar: O(n*n)
Matrice folosind Numpy
Creați o matrice folosind Numpy
Aici creăm o matrice Numpy folosind numpy.random și a modul aleator .
Python3
import> numpy as np> > # 1st argument -->numere cuprinse între 0 și 9,> # 2nd argument, row = 3, col = 3> array> => np.random.randint(> 10> , size> => (> 3> ,> 3> ))> print> (array)> |
>
>
Ieșire:
[[2 7 5] [8 5 1] [8 4 6]]>
Operații matematice matrice în Python folosind Numpy
Aici acoperim diferite operații matematice, cum ar fi adunarea, scăderea, înmulțirea și împărțirea folosind 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))> |
>
>
Ieșire:
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 ]]>
Punctați și încrucișați produsul cu Matrix
Aici, vom găsi produsele interioare, exterioare și încrucișate ale matricelor și vectorilor folosind NumPy în Python.
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)> |
>
>
Ieșire:
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]]>
Transpunerea matricei în Python folosind Numpy
Pentru a efectua operația de transpunere în matrice putem folosi numpy.transpose() metodă.
Python3
matrix> => [[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ]]> print> (> '
'> , numpy.transpose(matrix))> |
>
>
Ieșire:
[[1 4][2 5][3 6]]>
Creaza un matrice goală cu NumPy în Python
Inițializarea unei matrice goale, folosind 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)> |
>
>
Ieșire:
Matrix of 2x2: [[0 0] [0 0]] Matrix of 3x3: [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]>
Tăierea în Matrix folosind Numpy
Tăierea este procesul de a alege anumite rânduri și coloane dintr-o matrice și apoi de a crea o nouă matrice prin eliminarea tuturor elementelor neselectate. În primul exemplu, tipărim întreaga matrice, în al doilea trecem 2 ca index inițial, 3 ca ultimul indice și index jump ca 1. Același lucru este folosit în următoarea imprimare, tocmai am schimbat indexul sari la 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> ])> |
>
>
Ieșire:
[[ 6 8 10] [ 9 -12 15] [ 12 16 20] [ 15 -20 25]] Slicing Third Row-Second Column: [16] Slicing Third Row-Third Column: [20]>
Ștergeți rânduri și coloane folosind Numpy
Aici, încercăm să ștergem rânduri folosind funcția np.delete() . În cod, am încercat mai întâi să ștergem 0thrând, apoi am încercat să ștergem 2ndrând, apoi 3rdrând.
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)> |
>
>
Ieșire:
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]]>
Adăugați rânduri/coloane în matricea Numpy
Am adăugat încă o coloană la 4thpoziționați folosind 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))> |
>
>
Ieșire:
resultant array [[ 6 8 10 1] [ 9 -12 15 2] [ 15 -20 25 3]]>