Search code examples
pythonarrayspython-3.xnestedmultiplication

How to multiply elements in an array with each elements in another array using Python


I need help for my project. I have two arrays wherein I have to multiply the elements of array1 for each elements in array2.

As an example,

pop_i = [[1, 0, 1]
         [0, 0, 1]
         [1, 1, 0]]

r_q = [[3, 5, 2], [5, 4, 3], [5, 2, 2]] 

What I did first is to arrange r_q to become the array that I wanted.

# simply arranging the values by means of transposition or using zip
r_q = [[3, 5, 5], [5, 4, 2], [2, 3, 2]]

What I need to do now is to multiply the elements in r_q with each elements in pop_i, like:

r_10 = [3, 5, 5] * [1, 0, 1]
r_11 = [3, 5, 5] * [0, 0, 1]
r_12 = [3, 5, 5] * [1, 1, 0]

r_20 = [5, 4, 2] * [1, 0, 1]
r_21 = [5, 4, 2] * [0, 0, 1]
r_22 = [5, 4, 2] * [1, 1, 0]

r_30 = [2, 3, 2] * [1, 0, 1]
r_31 = [2, 3, 2] * [0, 0, 1]
r_32 = [2, 3, 2] * [1, 1, 0]

Afterwards, get their sums.

# r_1_sum = [3*1 + 5*0 + 5*1, 3*0 + 5*0 + 5*1, 3*1 + 5*1 + 5*0] and so on...

r_1_sum = [8, 5, 8]
r_2_sum = [7, 2, 9]
r_3_sum = [4, 2, 5]

I am having a hard time multiplying r_q with each elements in pop_i. So far, my code looks like this:

def fitness_score(g, u):
   # arrange resource demand of r_q 
   result = numpy.array([lst for lst in zip(*r_q)])

   # multiply elements in r_q with each elements in pop_i
   for i in range(0, len(result)):
      multiplied_output = numpy.multiply(result[i], pop_i)
   print(multiplied_output)

   for x in in range(0, len(multiplied_output)):
      final = numpy.sum(multiplied_output[x])

But I keep getting answer for the last index in r_q. I think the multiplication part is wrong. Any help/suggestion would be very much appreciated. Thank you so much!


Solution

  • Assuming,

    pop_i = [[1, 0, 1],[0, 0, 1],[1, 1, 0]]
    r_q = [[3, 5, 2], [5, 4, 3], [5, 2, 2]] 
    

    Use:

    matrix = []
    for row in zip(*r_q):
        temp = []
        for col in zip(*pop_i):
            temp.append(sum([x*y for x, y in zip(row, col)]))
        matrix.append(temp)
    
    r_1_sum, r_2_sum, r_3_sum = matrix
    

    Or, better use the numpy approach,

    import numpy as np
    
    a1 = np.array(pop_i)
    a2 = np.array(r_q)
    a = a1 @ a2
    r_1_sum, r_2_sum, r_3_sum = a.T.tolist()
    

    Result:

    [8, 5, 8] # r_1_sum
    [7, 2, 9] # r_2_sum
    [4, 2, 5] # r_3_sum