Aquí discutiremos diferentes formas de formar una matriz usando Python. En este tutorial también discutiremos las diversas operaciones que se pueden realizar en una matriz. También cubriremos el módulo externo Numpy para formar una matriz y sus operaciones en Python.

¿Qué es la matriz?
Una matriz es una colección de números dispuestos en una matriz rectangular en filas y columnas. En los campos de la ingeniería, la física, la estadística y los gráficos, las matrices se utilizan ampliamente para expresar rotaciones de imágenes y otros tipos de transformaciones.
La matriz se conoce como matriz m por n, denotada por el símbolo m x n si hay m filas yn columnas.
Creando una matriz simple usando Python
Método 1: crear una matriz con una lista de listas
Aquí, vamos a crear una matriz usando la lista de listas.
Python3
matrix> => [[> 1> ,> 2> ,> 3> ,> 4> ],> > [> 5> ,> 6> ,> 7> ,> 8> ],> > [> 9> ,> 10> ,> 11> ,> 12> ]]> print> (> 'Matrix ='> , matrix)> |
>
>
Producción:
Matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]>
Método 2: tomar la entrada de Matrix del usuario en Python
Aquí, tomamos varias filas y columnas del usuario e imprimimos la Matriz.
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> ()> |
>
>
Producción:
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>
Complejidad del tiempo: O(n*n)
Espacio auxiliar: O(n*n)
Método 3: crear una matriz mediante comprensión de listas
La comprensión de listas es una forma elegante de definir y crear una lista en Python. Estamos usando la función de rango para imprimir 4 filas y 4 columnas.
Python3
matrix> => [[column> for> column> in> range> (> 4> )]> for> row> in> range> (> 4> )]> print> (matrix)> |
>
>
Producción:
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]>
Asignación de valor en una matriz
Método 1: asignar valor a una celda individual en Matrix
Aquí estamos reemplazando y asignando valor a una celda individual (1 fila y 1 columna = 11) en la Matriz.
Python3
jpa en primavera
X> => [[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ], [> 7> ,> 8> ,> 9> ]]> row> => column> => 1> X[row][column]> => 11> print> (X)> |
>
>
Producción:
[[1, 2, 3], [4, 11 , 6], [7, 8, 9]]>
Método 2: asignar un valor a una celda individual usando indexación negativa en Matrix
Aquí estamos reemplazando y asignando valor a una celda individual (-2 filas y -1 columna = 21) en la Matriz.
Python3
it es
row> => -> 2> column> => -> 1> X[row][column]> => 21> print> (X)> |
>
>
Producción:
[[1, 2, 3], [4, 5, 21 ], [7, 8, 9]]>
Accediendo al valor en una matriz
Método 1: acceder a los valores de Matrix
Aquí, accedemos a los elementos de una Matriz pasando su fila y columna.
Python3
print> (> 'Matrix at 1 row and 3 column='> , X[> 0> ][> 2> ])> print> (> 'Matrix at 3 row and 3 column='> , X[> 2> ][> 2> ])> |
>
>
Producción:
Matrix at 1 row and 3 column= 3 Matrix at 3 row and 3 column= 9>
Método 2: acceder a los valores de Matrix mediante indexación negativa
Aquí, accedemos a elementos de una Matriz pasando su fila y columna en indexación negativa.
Python3
import> numpy as np> X> => [[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ], [> 7> ,> 8> ,> 9> ]]> print> (X[> -> 1> ][> -> 2> ])> |
>
>
Producción:
8>
Operaciones matemáticas con Matrix en Python
Ejemplo 1: Agregar valores a una matriz con un bucle for en Python
Aquí, estamos agregando dos matrices usando el bucle for de 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)> |
>
>
Producción:
[10, 10, 10] [10, 10, 10] [10, 10, 10]>
Complejidad del tiempo: O(n*n)
Espacio auxiliar: O(n*n)
Ejemplo 2: Sumar y restar valores a una matriz con comprensión de lista
Realizar la suma y resta básica usando la comprensión de listas.
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)> |
int a cadena java
>
>
Producción:
Matrix Addition [10, 10, 10] [10, 10, 10] [10, 10, 10] Matrix Subtraction [-8, -6, -4] [-2, 0, 2] [4, 6, 8]>
Complejidad del tiempo: O(n*n)
Espacio auxiliar: O(n*n)
Ejemplo 3: programa Python para multiplicar y dividir dos matrices
Realizar la multiplicación y división básica usando el bucle de 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)> |
>
>
Producción:
Matrix Multiplication [9, 16, 21] [24, 25, 24] [21, 16, 9] Matrix Division [0, 0, 0] [0, 1, 1] [2, 4, 9]>
Complejidad del tiempo: O(n*n)
Espacio auxiliar: O(n*n)
Transponer en matriz
Ejemplo: programa Python para transponer una matriz usando un bucle
La transpuesta de una matriz se obtiene cambiando filas a columnas y columnas a filas. En otras palabras, la transposición de A[][] se obtiene cambiando A[i][j] por 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)> |
>
>
Producción:
[9, 6, 3] [8, 5, 2] [7, 4, 1]>
Complejidad del tiempo: O(n*n)
Espacio auxiliar: O(n*n)
Matriz usando Numpy
Crea una matriz usando Numpy
Aquí estamos creando una matriz Numpy usando numpy.random y un módulo aleatorio .
Python3
centos vs rhel
import> numpy as np> > # 1st argument -->números que van del 0 al 9,> # 2nd argument, row = 3, col = 3> array> => np.random.randint(> 10> , size> => (> 3> ,> 3> ))> print> (array)> |
>
>
Producción:
[[2 7 5] [8 5 1] [8 4 6]]>
Operaciones matemáticas matriciales en Python usando Numpy
Aquí cubrimos diferentes operaciones matemáticas como suma, resta, multiplicación y división usando 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))> |
>
>
Producción:
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 ]]>
Producto punto y cruz con Matrix
Aquí encontraremos los productos interno, externo y cruzado de matrices y vectores usando NumPy en 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)> |
>
>
Producción:
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]]>
Transposición de matrices en Python usando Numpy
Para realizar la operación de transposición en matriz podemos usar el numpy.transponer() método.
Python3
matrix> => [[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ]]> print> (> '
'> , numpy.transpose(matrix))> |
>
>
Producción:
[[1 4][2 5][3 6]]>
Crear un matriz vacía con NumPy en Python
Inicializando una matriz vacía, usando el np.ceros() .
Python3
a> => np.zeros([> 2> ,> 2> ], dtype> => int> )> print> (> '
Matrix of 2x2:
'> , a)> c> => np.zeros([> 3> ,> 3> ])> print> (> '
Matrix of 3x3:
'> , c)> |
>
>
Producción:
Matrix of 2x2: [[0 0] [0 0]] Matrix of 3x3: [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]>
rebanar en Matrix usando Numpy
Cortar es el proceso de elegir filas y columnas específicas de una matriz y luego crear una nueva matriz eliminando todos los elementos no seleccionados. En el primer ejemplo, imprimimos la matriz completa, en el segundo pasamos 2 como índice inicial, 3 como último índice y el salto de índice como 1. Se usa lo mismo en la siguiente impresión, acabamos de cambiar el índice. salta a 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> ])> |
>
>
comparar con cadenas en java
Producción:
[[ 6 8 10] [ 9 -12 15] [ 12 16 20] [ 15 -20 25]] Slicing Third Row-Second Column: [16] Slicing Third Row-Third Column: [20]>
Eliminar filas y columnas usando Numpy
Aquí, estamos intentando eliminar filas usando la función np.delete(). En el código, primero intentamos eliminar el 0.thfila, luego intentamos eliminar los 2Dakota del Nortefila, y luego la 3tercerofila.
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)> |
>
>
Producción:
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]]>
Agregar filas/columnas en la matriz Numpy
Agregamos una columna más en el 4thposición usando 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))> |
>
>
Producción:
resultant array [[ 6 8 10 1] [ 9 -12 15 2] [ 15 -20 25 3]]>