Open In App

Python – Matrix Custom Multiplier

Last Updated : 04 Apr, 2023
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.



Similar Reads

Python - Convert Matrix to Custom Tuple Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to perform conversion of a Python Matrix to matrix of tuples which a value attached row-wise custom from external list. This kind of problem can have applications in data domains as Matrix is integral DS that is used. Let's discuss certain ways in which this task ca
6 min read
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 comprehension The zip function combined with the list comprehe
6 min read
Python Program to sort rows of a matrix by custom element count
Given Matrix, the following program shows how to sort rows of a matrix by the count of presence of numbers from a specified list. Input : test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]], cus_list = [4, 5, 7] Output : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]] Explanation : 0 < 1 = 1 < 3 is order of custom elements count.Input : test_list
5 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 performed. Input : test_list = [(5, 6, 7, 8)] vals
4 min read
Python - Custom Columns Matrix
Sometimes, while working with Python lists, we can have a problem in which we need to extract certain columns from Matrix and recreate it. This kind of problem can have applications in data domains as they use Matrix as a prominent input parameter. Let's discuss certain ways in which this task can be performed. Input : test_list = [[5, 4, 3, 4], [7
5 min read
Add custom borders to matrix in Python
Given a Matrix, the task is to write a python program to print each row having custom borders. Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], bord = "|" Output : | 4 5 6 | | 1 4 5 | | 6 9 1 | | 0 3 1 | Explanation : Matrix is ended using | border as required.Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], bord =
5 min read
Python program to Convert a Matrix to Sparse Matrix
Given a matrix with most of its elements as 0, we need to convert this matrix into a sparse matrix in Python. Example: Input: Matrix: 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 5 0 0 0 Output: Sparse Matrix: 0 0 1 1 1 2 2 2 3 3 3 4 4 0 5 Explanation: Here the Matrix is represented using a 2D list and the Sparse Matrix is represented in the form Row Column Val
3 min read
Python - Convert Integer Matrix to String Matrix
Given a matrix with integer values, convert each element to String. Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]] Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] Explanation : All elements of Matrix converted to Strings. Input : test_list = [[4, 5, 7], [10, 8, 3]] Output : [['4', '5', '7'], ['10', '8', '3']] Explanation : A
6 min read
Convert covariance matrix to correlation matrix using Python
In this article, we will be discussing the relationship between Covariance and Correlation and program our own function for calculating covariance and correlation using python. Covariance: It tells us how two quantities are related to one another say we want to calculate the covariance between x and y the then the outcome can be one of these. [Tex]
5 min read
Python Program to Convert String Matrix Representation to Matrix
Given a String with matrix representation, the task here is to write a python program that converts it to a matrix. Input : test_str = "[gfg,is],[best,for],[all,geeks]"Output : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]Explanation : Required String Matrix is converted to Matrix with list as data type. Input : test_str = "[gfg,is],[for],[all
4 min read