Python - Matrix Custom Multiplier
Last Updated :
04 Apr, 2023
Sometimes, while working with data, we can have a problem in which we need to multiply each row of matrix with a different multiplier. This kind of application is important in data science domain. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + zip() The combination of above functions can be used to perform this task. In this, we iterate through each row and perform the task of multiplication using zip().
Step by step approach:
- Initialize two lists test_list1 and test_list2 with some values.
- Print the original test_list1 and test_list2 using the print() function.
- Initialize an empty list res which will store the result of matrix multiplication.
- Use a for loop and the zip() function to iterate over the elements of test_list2 and test_list1 simultaneously. The zip() function returns an iterator that combines the elements of two or more sequences into tuples.
- For each iteration, the loop assigns mul to the corresponding element of test_list2 and sub to the corresponding sub-list of test_list1.
- Initialize an empty list temp which will store the result of multiplying the elements of sub with mul.
- Use another for loop to iterate over the elements of sub.
- For each iteration, the loop multiplies mul with the current element of sub and appends the result to temp.
- After the inner for loop completes, append temp to res which will store the result of matrix multiplication.
- After the outer for loop completes, print the resulting matrix res using the print() function.
Python3
# Python3 code to demonstrate
# Matrix Custom Multiplier
# using loop + zip()
# Initializing list
test_list1 = [[1, 3], [5, 6], [8, 9]]
test_list2 = [4, 3, 6]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Matrix Custom Multiplier
# using loop + zip()
res = []
for mul, sub in zip(test_list2, test_list1):
temp = []
for ele in sub:
temp.append(mul * ele)
res.append(temp)
# printing result
print ("Matrix after custom multiplication : " + str(res))
OutputThe original list 1 is : [[1, 3], [5, 6], [8, 9]]
The original list 2 is : [4, 3, 6]
Matrix after custom multiplication : [[4, 12], [15, 18], [48, 54]]
Time complexity: O(n^2), where n is the length of the longest sublist in test_list1.
Auxiliary space: O(n^2), to store the result list res.
Method #2 : Using list comprehension + zip() The combination of above methods can be used to solve this problem. In this, we just iterate through the list and perform the task of multiplication in one liner.
Python3
# Python3 code to demonstrate
# Matrix Custom Multiplier
# using list comprehension + zip()
# Initializing list
test_list1 = [[1, 3], [5, 6], [8, 9]]
test_list2 = [4, 3, 6]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Matrix Custom Multiplier
# using list comprehension + zip()
res = [[mul * ele for ele in sub] for mul, sub in zip(test_list2, test_list1)]
# printing result
print ("Matrix after custom multiplication : " + str(res))
OutputThe original list 1 is : [[1, 3], [5, 6], [8, 9]]
The original list 2 is : [4, 3, 6]
Matrix after custom multiplication : [[4, 12], [15, 18], [48, 54]]
Time complexity: O(n^2), where n is the number of elements in the matrix.
Auxiliary space: O(n^2), since a new matrix of the same size is created to store the result.
Method #3 : Using Numpy
We can use Numpy library to perform this task. Numpy library provides a function “multiply()” which is used to perform the element wise multiplication of two arrays.
Python3
# Python3 code to demonstrate
# Matrix Custom Multiplier
# using Numpy
# Importing Numpy library
import numpy as np
# Initializing list
test_list1 = [[1, 3], [5, 6], [8, 9]]
test_list2 = [4, 3, 6]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
test_list2 = np.array([4, 3, 6])[:, np.newaxis]
# Matrix Custom Multiplier
# using Numpy
res = np.multiply(test_list1, test_list2)
# printing result
print("Matrix after custom multiplication : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
Output :
The original list 1 is : [[1, 3], [5, 6], [8, 9]]
The original list 2 is : [4, 3, 6]
Matrix after custom multiplication : [[ 4 9]
[15 18]
[48 54]]
Time Complexity: O(mn), where m is the number of rows and n is the number of columns.
Auxiliary Space: O(mn)
Method #4 : Using for loops
Python3
# Python3 code to demonstrate
# Matrix Custom Multiplier
# Initializing list
test_list1 = [[1, 3], [5, 6], [8, 9]]
test_list2 = [4, 3, 6]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Matrix Custom Multiplier
res = []
for i in range(0,len(test_list1)):
x=[]
for j in range(0,len(test_list1[i])):
x.append(test_list1[i][j]*test_list2[i])
res.append(x)
# printing result
print ("Matrix after custom multiplication : " + str(res))
OutputThe original list 1 is : [[1, 3], [5, 6], [8, 9]]
The original list 2 is : [4, 3, 6]
Matrix after custom multiplication : [[4, 12], [15, 18], [48, 54]]
Time Complexity: O(mn), where m is the number of rows and n is the number of columns.
Auxiliary Space: O(mn)
Method #5: Using the map() function
This implementation uses the lambda function inside the map() function to perform the multiplication on each element of the sub-lists. The outer map() function applies the lambda function to each element of both input lists using the zip() function. Finally, the result is converted to a list using the list() function.
Python3
# Python3 code to demonstrate
# Matrix Custom Multiplier
# using map() function
# Initializing list
test_list1 = [[1, 3], [5, 6], [8, 9]]
test_list2 = [4, 3, 6]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Matrix Custom Multiplier
# using map() function
res = list(map(lambda x, y: list(map(lambda a: a*x, y)), test_list2, test_list1))
# printing result
print ("Matrix after custom multiplication : " + str(res))
OutputThe original list 1 is : [[1, 3], [5, 6], [8, 9]]
The original list 2 is : [4, 3, 6]
Matrix after custom multiplication : [[4, 12], [15, 18], [48, 54]]
The time complexity of this code is O(n^2), where n is the length of the longest sub-list in the input list test_list1.
The space complexity of this code is O(n^2), where n is the length of the longest sub-list in the input list test_list1.
Method 6: Using pandas
Step-by-step approach:
- Import pandas library
- Create a pandas DataFrame using the first list "test_list1"
- Multiply the DataFrame with the second list "test_list2" using the multiply() method of DataFrame
- Get the resulting matrix as a numpy array using the values attribute of the DataFrame
- Convert the numpy array back to a list using the tolist() method of numpy array.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate
# Matrix Custom Multiplier
# using pandas
# import pandas and numpy
import pandas as pd
import numpy as np
# Initializing list
test_list1 = [[1, 3], [5, 6], [8, 9]]
test_list2 = [4, 3, 6]
# Create a pandas DataFrame
df = pd.DataFrame(test_list1)
# Multiply the DataFrame with the second list
res_df = df.multiply(test_list2, axis=0)
# Get the resulting matrix as a numpy array
res_np = res_df.values
# Convert the numpy array back to a list
res = res_np.tolist()
# printing result
print ("Matrix after custom multiplication : " + str(res))
Output:
Matrix after custom multiplication : [[4, 12], [15, 18], [48, 54]]
Time complexity: O(n^2), where n is the number of elements in the largest dimension of the matrix (either number of rows or columns).
Auxiliary space: O(n^2), since the matrix multiplication operation requires creating a new matrix of size n x n
Method 7: "Custom matrix multiplication using NumPy"
Step 1: Initialize an empty list res_list.
Step 2: Use nested for loops to iterate over the elements of test_list1 and test_list2.
Step 3: Multiply each element of test_list1 with the corresponding element of test_list2 and append the result to res_list.
Step 4: Convert res_list to a NumPy array using np.array().
Step 5: Reshape the NumPy array to match the dimensions of test_list1.
Step 6: Convert the NumPy array back to a list using tolist() method.
Step 7: Print the resulting matrix.
Python3
import numpy as np
# Initializing list
test_list1 = [[1, 3], [5, 6], [8, 9]]
test_list2 = [4, 3, 6]
# Initializing an empty list for the result
res_list = []
# Using nested for loops to multiply the lists
for i in range(len(test_list1)):
row = []
for j in range(len(test_list1[i])):
row.append(test_list1[i][j] * test_list2[i])
res_list.append(row)
# Converting the result list to a NumPy array
res_np = np.array(res_list)
# Reshaping the NumPy array to match the dimensions of test_list1
res_np = np.reshape(res_np, np.shape(test_list1))
# Converting the NumPy array back to a list
res = res_np.tolist()
# Printing the resulting matrix
print("Matrix after custom multiplication : " + str(res))
OUTPUT:
Matrix after custom multiplication : [[4, 12], [15, 18], [48, 54]]
Time complexity of this method is O(n^2)
The auxiliary space required is O(n^2), where n is the size of test_list1.
Similar Reads
Python | Custom length Matrix Sometimes, we need to initialize a matrix in Python of variable length from the list containing elements. In this article, we will discuss the variable length method initialization and certain shorthands to do so. Let's discuss certain ways to perform this. Method #1: Using zip() + list comprehensio
6 min read
Python - Constant Multiplication over List We are given a list we need to multiply each element in the list by a constant. For example, we are having a list a = [1, 2, 3, 4, 5] and constant c=2 we need to multiply this constant in whole list.Using List ComprehensionList comprehension allows us to multiply each element in list by a constant b
3 min read
Matrix Product - Python The task of calculating the matrix product in Python involves finding the product of all elements within a matrix or 2D list . This operation requires iterating through each element in the matrix and multiplying them together to obtain a single cumulative product. For example, given a matrix a = [[1
3 min read
Python - Multiply Two Lists We are given two list we need to multiply given two list. For example, we are having two lists a = [1, 2, 3] b = [4, 5, 6] we need to multiply list so that the resultant output should be [4, 10, 18].Using a LoopWe can multiply two lists element-wise using a loop by iterating over both lists and mult
2 min read
Python Program to Multiply Two Matrices Given two matrices, we will have to create a program to multiply two matrices in Python. Example: Python Matrix Multiplication of Two-DimensionPythonmatrix_a = [[1, 2], [3, 4]] matrix_b = [[5, 6], [7, 8]] result = [[0, 0], [0, 0]] for i in range(2): for j in range(2): result[i][j] = (matrix_a[i][0]
5 min read
Python - Matrix creation of n*n Matrices are fundamental structures in programming and are widely used in various domains including mathematics, machine learning, image processing, and simulations. Creating an nÃn matrix efficiently is an important step for these applications. This article will explore multiple ways to create such
3 min read
Python - Add custom dimension in Matrix Sometimes, while working with Python Matrix, we can have a problem in which we need to add another dimension of custom values, this kind of problem can have problem in all kinds of domains such as day-day programming and competitive programming. Let's discuss certain ways in which this task can be p
4 min read
Python Program to check Involutory Matrix Given a matrix and the task is to check matrix is an involutory matrix or not. Involutory Matrix: A matrix is said to be an involutory matrix if the matrix multiplies by itself and returns the identity matrix. The involutory matrix is the matrix that is its own inverse. The matrix A is said to be an
3 min read
Python Program to Construct n*m Matrix from List We are given a list we need to construct a n*m matrix from that list. For example, a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] we need to construct a 3*4 matrix so that resultant output becomes [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] .Using List ComprehensionThis method uses list comprehension
3 min read
Summation Matrix columns - Python The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
2 min read