Home > Blockchain >  How to simplify for loops using matrix multiplication?
How to simplify for loops using matrix multiplication?

Time:05-06

Is there a more efficient way to replace these 2 for loops with matrix multiplication?

def cost_func(x, y):
     
    for i in range(24):
        for j in range(24):
            cost = np.sum(W[i][j]*(y[j] - x[i]))       
    
    return cost

W is a matrix (25,25) and x,y are vectors with 25 elements.

CodePudding user response:

Not 100% sure what you are trying to achieve here since as @Tim Roberts pointed out you are not saving the costs. Also the np.sum is confusing assuming x and y are 1d vectors. But if they are 1d vectors you could do:

import numpy as np
x = np.arange(24)
y = np.arange(24)
W = np.random.uniform(0, 1, (24, 24))
cost = (W * (y.reshape(1, -1) - x.reshape(-1, 1)))

# cost[i][j] = W[i][j]*(y[j] - x[i])

CodePudding user response:

numpy supports a matrix multiply operator, @. I think you can get what you want by:

C:\tmp>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> x = np.arange(3).reshape(1,3)
>>> y = np.arange(4)
>>> W = np.ones((3,4))
>>> (-x)@W@y
array([-18.])
>>>
  • Related