Open In App

Python – Matrix Custom Multiplier

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Initialize two lists test_list1 and test_list2 with some values.
  2. Print the original test_list1 and test_list2 using the print() function.
  3. Initialize an empty list res which will store the result of matrix multiplication.
  4. 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.
  5. For each iteration, the loop assigns mul to the corresponding element of test_list2 and sub to the corresponding sub-list of test_list1.
  6. Initialize an empty list temp which will store the result of multiplying the elements of sub with mul.
  7. Use another for loop to iterate over the elements of sub.
  8. For each iteration, the loop multiplies mul with the current element of sub and appends the result to temp.
  9. After the inner for loop completes, append temp to res which will store the result of matrix multiplication.
  10. 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))


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, 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))


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, 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))


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, 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))


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, 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.



Last Updated : 04 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads