Posted on by Kalkicode
Code Python Core

Python Matrix

In the Python programming language, a matrix is a 2-dimensional rectangular collection of elements. These elements are represented by set of rows and columns. A matrix is consists equal number of elements in every row.

In python matrix can be created in two ways. First by using list and second by using Numpy array.

Create matrix using python multilist

Generate [NxN] matrix by using of 2d list.

# matrix using 2d list
matrix = [[1,2,3,4],
          [5,6,7,8],
          [8,7,6,5],
          [4,3,2,1]]
# print element
print(matrix)
[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]]
Python matrix using 2d list

In the above image showing how to access and operate on a matrix element. Suppose we are to reach the third element in the second row. For example

# matrix using 2d list
matrix = [[1,2,3,4],
          [5,6,7,8],
          [8,7,6,5],
          [4,3,2,1]]
# Get 2nd row 3rd element
print(matrix[2][3]) # 5

Size of matrix can be [NXM], Here N indicates number of rows and M indicates number of columns.

Create matrix using Numpy array

import numpy as np
# create matrix
matrix = np.array([[1,2,3,4],[5,6,7,8],[8,7,6,5],[4,3,2,1]])
# print element
print(matrix)
[[1 2 3 4]
 [5 6 7 8]
 [8 7 6 5]
 [4 3 2 1]]

Matrix operation using Numpy array

import numpy as np
# Create matrixs
x = np.array([[5,2,3],[5,6,7],[4,8,9]])
y = np.array([[1,2,3],[3,6,1],[1,2,2]])

# Basic operation
# Addition
add = x + y
# Multiplication
mul = x * y
# Subtraction
sub = x - y

print(" Addition x + y")
print(add)

print(" Multiplication x * y")
print(mul)

print(" Subtraction x - y")
print(sub)
 Addition x + y
[[ 6  4  6]
 [ 8 12  8]
 [ 5 10 11]]
 Multiplication x * y
[[ 5  4  9]
 [15 36  7]
 [ 4 16 18]]
 Subtraction x - y
[[4 0 0]
 [2 0 6]
 [3 6 7]]

This is basic matrix operations which is generally used.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment