logo

Python Matrix

În acest tutorial, vom afla despre matricele Python. În Python, un obiect matrice este similar cu listele imbricate, deoarece sunt multidimensionale. Vom vedea cum să creăm o matrice folosind matrice Numpy. În continuare, vom vedea diverse metode de operații cu matrice și exemple pentru o mai bună înțelegere.

Ce este o matrice în Python?

O matrice în Python este o matrice Numpy dreptunghiulară. Această matrice trebuie să fie bidimensională. Conține date stocate în rândurile și coloanele matricei. Într-o matrice Python, seria orizontală de elemente este denumită „rânduri”, în timp ce seria verticală de elemente este denumită „coloane”. Rândurile și coloanele sunt stivuite unele peste altele la fel ca o listă imbricată. Dacă o matrice conține r număr de rânduri și c număr de coloane, unde r și c sunt numere întregi pozitive, atunci r x c determină ordinea acestui obiect matrice.

Putem stoca șiruri de caractere, numere întregi și obiecte de alte tipuri de date într-o matrice. Datele sunt stocate în stive de rânduri și coloane într-o matrice. Matricea este o structură de date crucială pentru calcule în matematică și știință. În Python, considerăm o listă de liste sau o listă imbricată ca o matrice, deoarece Python nu include niciun tip încorporat pentru un obiect matrice.

Pe parcursul acestui tutorial, vom parcurge următoarea listă de metode de operare a matricei.

  • Adăugarea matricei
  • Înmulțirea matricei
  • Operator de multiplicare matrice
  • Înmulțirea matriceală fără Numpy
  • Matrice inversă
  • Transpunerea matricei
  • Matrice la matrice

Cum funcționează Matricele în Python?

Scriem datele într-o matrice bidimensională pentru a crea o matrice. Se face astfel:

Exemplu

 [ 2 3 5 7 6 3 2 6 7 2 5 7 2 6 1 ] 

Afișează o matrice cu 3 rânduri și 5 coloane, deci dimensiunea sa este 3×5. Obiectele de tip de date întregi alcătuiesc datele din această matrice. Rândul 1, primul rând, are valori (2, 3, 5, 7, 6), în timp ce Rândul 2 are valori (3, 2, 6, 7, 2) iar Rândul 3 are valori 5, 7, 2, 6, 1. În ceea ce privește coloane, Coloana 1 are valori (2, 3, 5), Coloana 2 are valori (3, 2, 7) și așa mai departe.

Exemplu

 [ 0, 0, 1 0, 1, 0 1, 0, 0 ] 

Afișează o matrice cu 3 rânduri și 3 coloane, deci dimensiunea sa este 3×3. Astfel de matrici care au rânduri și coloane egale se numesc matrici pătrate.

În mod similar, Python permite utilizatorilor să-și stocheze datele într-o matrice dimensională m x n. Putem efectua adăugarea de matrici, înmulțirea, transpunerea și alte operații pe o structură asemănătoare matricei.

Implementarea unui obiect matrice în Python nu este simplă. Putem crea o matrice Python folosind matrice și le putem folosi în mod similar.

NumPy Array

Software-ul de calcul științific NumPy acceptă un obiect matrice N-dimensional robust. Instalarea NumPy este o condiție prealabilă pentru a-l folosi în programul nostru.

NumPy poate fi folosit și importat după instalare. Cunoașterea elementelor de bază ale Numpy Array va fi de ajutor în înțelegerea matricelor.

Matricele cu dimensiuni multiple ale elementelor sunt furnizate de NumPy. Iată o ilustrare:

Cod

 # Python program to show how to create a Numpy array # Importing numpy import numpy as np # Creating a numpy array array = np.array([4, 6, 'Harry']) print(array) print('Data type of array object: ', type(array)) 

Ieșire:

 ['4' '6' 'Harry'] Data type of array object: 

După cum putem vedea, tablourile Numpy aparțin clasei ndarray.

Exemplu pentru a crea o matrice folosind Numpy Array

Gândiți-vă la scenariul în care creăm o înregistrare a notelor elevilor. Vom înregistra numele și notele elevului la două materii, programare Python și Matrix. Vom crea o matrice bidimensională folosind o matrice numpy și apoi o vom remodela.

Cod

 # Python program to create a matrix using numpy array # Importing numpy import numpy as np # Creating the matrix record = np.array( [['Itika', 89, 91], ['Aditi', 96, 82], ['Harry', 91, 81], ['Andrew', 87, 91], ['Peter', 72, 79]]) matrix = np.reshape(record, (5,3)) print('The matrix is: 
', matrix) 

Ieșire:

 The matrix is: [['Itika' '89' '91'] ['Aditi' '96' '82'] ['Harry' '91' '81'] ['Andrew' '87' '91'] ['Peter' '72' '79']] 

Exemplu pentru a crea o matrice folosind metoda Numpy Matrix

Putem folosi numpy.matrix pentru a crea o matrice 2D.

Cod

 # Python program to show how to create a matrix using the matrix method # importing numpy import numpy as np # Creating a matrix matrix = np.matrix('3,4;5,6') print(matrix) 

Ieșire:

 [[3 4] [5 6]] 

Accesarea valorilor unei matrice

Indicii unei matrice pot fi folosiți pentru a accesa elementele stocate în ea. Datele stocate într-o matrice sunt accesibile utilizând aceeași abordare pe care o folosim pentru o matrice bidimensională.

Cod

 # Python program to access elements of a matrix # Importing numpy import numpy as np # Creating the matrix record = np.array( [['Itika', 89, 91], ['Aditi', 96, 82], ['Harry', 91, 81], ['Andrew', 87, 91], ['Peter', 72, 79]]) matrix = np.reshape(record, (5,3)) # Accessing record of Itika print( matrix[0] ) # Accessing marks in the matrix subject of Andrew print( 'Andrew's marks in Matrix subject: ', matrix[3][2] ) 

Ieșire:

 ['Itika' '89' '91'] Andrew's marks in Matrix subject: 91 

Metode de a crea o matrice Numpy 2-D sau o matrice

Există mai multe metode pentru a crea o matrice NumPy bidimensională și, prin urmare, o matrice. Furnizarea de intrări pentru rânduri și coloane

java localdate

Putem furniza numere întregi, flotanți sau chiar numere complexe. Folosind atributul dtype al metodei array, putem specifica tipul de date pe care îl dorim.

Cod

 # Python program to show how to create a Numpy array # Importing numpy import numpy as np # Creating numpy arrays array1 = np.array([[4, 2, 7, 3], [2, 8, 5, 2]]) print('Array of data type integers: 
', array1) array2 = np.array([[1.5, 2.2, 3.1], [3, 4.4, 2]], dtype = 'float') print('Array of data type float: 
', array2) array3 = np.array([[5, 3, 6], [2, 5, 7]], dtype = 'complex') print('Array of data type complex numbers: 
', array3) 

Ieșire:

 Array of data type integers: [[4 2 7 3] [2 8 5 2]] Array of data type float: [[1.5 2.2 3.1] [3. 4.4 2. ]] Array of data type complex numbers: [[5.+0.j 3.+0.j 6.+0.j] [2.+0.j 5.+0.j 7.+0.j]] 

Matrice având zero și unu

Cod

 # Python program to show how to create a Numpy array having zeroes and ones # Importing numpy import numpy as np # Creating numpy arrays zeores_array = np.zeros( (3, 2) ) print(zeores_array) ones_array = np.ones( (2, 4), dtype=np.int64 ) print(ones_array) 

Ieșire:

 [[0. 0.] [0. 0.] [0. 0.]] [[1 1 1 1] [1 1 1 1]] 

Aici, am specificat dtype la 64 de biți.

Folosind metodele arange() și shape().

Cod

 # Python program to show how to create Numpy array using arrange() and shape() methods # Importing numpy import numpy as np # Creating numpy arrays array1 = np.arange( 5 ) print(array1) array2 = np.arange( 6 ).reshape( 2, 3 ) print(array2) 

Ieșire:

 [0 1 2 3 4] [[0 1 2] [3 4 5]] 

Operații cu matrice Python

Adăugarea matricei Python

Vom adăuga cele două matrice și vom folosi bucla imbricată for prin matricele date.

Cod

 # Python program to add two matrices without using numpy # Creating matrices in the form of nested lists matrix1 = [[23, 43, 12], [43, 13, 55], [23, 12, 13]] matrix2 = [[4, 2, -1], [5, 4, -34], [0, -4, 3]] matrix3 = [[0,1,0], [1,0,0], [0,0,1]] matrix4 = [[0,0,0], [0,0,0], [0,0,0]] matrices_length = len(matrix1) #Adding the three matrices using nested loops for row in range(len(matrix1)): for column in range(len(matrix2[0])): matrix4[row][column] = matrix1[row][column] + matrix2[row][column] + matrix3[row][column] #Printing the final matrix print('The sum of the matrices is = ', matrix4) 

Ieșire:

 The sum of the matrices is = [[27, 46, 11], [49, 17, 21], [23, 8, 17]] 

Înmulțirea matricei Python

Operator de multiplicare a matricei Python

În Python @ este cunoscut ca operator de multiplicare. Să vedem un exemplu în care vom folosi acest operator pentru a înmulți două matrice.

Cod

 # Python program to show how to create a matrix using the matrix method. # importing numpy import numpy as np # Creating the matrices matrix1 = np.matrix('3,4;5,6') matrix2 = np.matrix('4,6;8,2') # Usng multiplication operator to multiply two matrices print(matrix1 @ matrix2) 

Ieșire:

 [[44 26] [68 42]] 

Înmulțirea matricelor Python fără a utiliza Numpy

O altă modalitate de a multiplica două matrice este utilizarea buclelor imbricate. Iată un exemplu de arătat.

Cod

 # Python program to show how to create a matrix using the matrix method # importing numpy import numpy as np # Creating two matrices matrix1 = [[4, 6, 2], [7, 4, 8], [6, 2, 7]] matrix2 = [[4, 6, 8, 2], [6, 5, 3, 7], [7, 3, 7, 6]] # Result will be a 3x4 matrix output = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # Iterating through the rows of matrix1 for i in range(len(matrix1)): # iterating through the columns of matrix2 for j in range(len(matrix2[0])): # iterating through the rows of matrix2 for k in range(len(matrix2)): output[i][j] += matrix1[i][k] * matrix2[k][j] for row in output: print(row) 

Ieșire:

 [66, 60, 64, 62] [108, 86, 124, 90] [85, 67, 103, 68] 

Python Matrix Inverse

Când o ecuație trebuie rezolvată pentru a obține valoarea unei variabile necunoscute care satisface ecuațiile, se calculează inversul unei matrice, care este doar reciproca matricei așa cum am face-o în matematica obișnuită. Inversa unei matrice este matricea care dă matricea de identitate atunci când înmulțim cu matricea originală. Doar o matrice nesingulară poate avea o inversă. O matrice nesingulară are un determinant diferit de zero.

Cod

 # Python program to show how to calculate the inverse of a matrix # Importing the required library import numpy as np # Creating a matrix A = np.matrix('3, 4, 6; 6, 2, 7; 6, 4, 6') # Calculating the inverse of A print(np.linalg.inv(A)) 

Ieșire:

 [[-3.33333333e-01 -7.40148683e-17 3.33333333e-01] [ 1.25000000e-01 -3.75000000e-01 3.12500000e-01] [ 2.50000000e-01 2.50000000e-01 -3.75000000e-01]] 

Python Matrix Transpose

Python Matrix Transpose fără Numpy

Transpunerea unei matrice implică schimbarea rândurilor și coloanelor. Are simbolul X'. Vom pune obiectul în rândul i și coloana j a matricei X în rândul j și coloana i a matricei X'. În consecință, X’ va deveni o matrice 4x3 dacă matricea originală X este o matrice 3x4.

Cod

 # Python program to find the transpose of a matrix using nested loops # Creating a matrix matrix = [[4, 6, 7, 8], [3, 7, 2, 7], [7, 3, 7, 5]] result = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] # iterating through the rows for i in range(len(matrix)): # iterating through the columns for j in range(len(matrix[0])): result[j][i] = matrix[i][j] for row in result: print(row) 

Ieșire:

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

Python Matrix Transpose folosind Numpy

Putem folosi metoda matrix.transpose() în Numpy pentru a obține transpunerea matricei.

Cod

 # Python program to find the transpose of a matrix # importing the required module import numpy as np # Creating a matrix using matrix method matrix = np.matrix('[5, 7, 6; 4, 2, 4]') #finding transpose using matrix.transpose method transpose = matrix.transpose() print(transpose) 

Ieșire:

 [[5 4] [7 2] [6 4]] 

Conversia Python Matrix în Array

Putem folosi funcțiile ravel și flatten pentru a converti o matrice Python într-o matrice Python.

Cod

 # Python program to convert a matrix to an array # importing the required module import numpy as np # Creating a matrix using numpy matrix = np.matrix('[4, 6, 7; 5, 2, 6; 6, 3, 6]') # Using ravel() function to covert matrix to array array = matrix.ravel() print(array) # Using flatten() function to covert matrix to array array = np.asarray(matrix).flatten() print(array) # Using reshape() function to covert matrix to array array = (np.asarray(matrix)).reshape(-1) print(array) 

Ieșire:

 [[4 6 7 5 2 6 6 3 6]] [4 6 7 5 2 6 6 3 6] [4 6 7 5 2 6 6 3 6]