Tutorial for Column Wise Multiplication of Two matrix by lists in python
suppose we want to multiply two lists of different lengths in python how to do it?Well there are many ways of Doing it
from itertools we can use map but it multiples lists of equal length only
using numpy but creating numpy arrays are not so useful it includes complicated stuff
here ill show you can do it simply using logic
Suppose i have a 2d array and i want to multiply it column wise
[ 1 2 3 ] [1] [1, 4, 7]
[ 4 5 6 ] * [2] = [2, 5, 8]
[ 7 8 9 ] [3] [3, 6, 9]
So in python we create a list inside a list
a=[[1,2,3],[4,5,6],[7,8,9]]
b=[1,2,3]
for row in range(len(a)):
print([a[col][row] for col in range(len(b)) ])
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
mul=[[1, 2, 3, 4, 0, 0], [0, 1, 2, 3, 4, 0], [0, 0, 1, 2, 3, 4], [4, 0, 0, 1, 2, 3], [3, 4, 0, 0, 1, 2], [2, 3, 4, 0, 0, 1]]
hn=[-3, 2, 1, 0, 0, 0]
so the ans should be
[[-3, 0, 0, 0, 0, 0], [-6, 2, 0, 0, 0, 0], [-9, 4, 1, 0, 0, 0], [-12, 6, 2, 0, 0, 0], [0, 8, 3, 0, 0, 0], [0, 0, 4, 0, 0, 0]]
for i in range(len(xn)):
print([mul[j][i]*hn[j] for j in range(len(hn))])
[-3, 0, 0, 0, 0, 0]
[-6, 2, 0, 0, 0, 0]
[-9, 4, 1, 0, 0, 0]
[-12, 6, 2, 0, 0, 0]
[0, 8, 3, 0, 0, 0]
[0, 0, 4, 0, 0, 0]
Now if we Want to add the ans to another list we simply do
next=[]
for i in range(len(xn)):
next.append( list(mul[j][i]*hn[j] for j in range(len(hn))))
print(next)
[[-3, 0, 0, 0, 0, 0], [-6, 2, 0, 0, 0, 0], [-9, 4, 1, 0, 0, 0], [-12, 6, 2, 0, 0, 0], [0, 8, 3, 0, 0, 0], [0, 0, 4, 0, 0, 0]]
Comments
Post a Comment