Trying to vectorize iterative calculation with numpy

前端 未结 3 623
天命终不由人
天命终不由人 2021-01-05 05:15

I am trying to make some piece of code more efficient by using the vectorized form in numpy. Let me show you an example so you know what I mean.

Given the following

3条回答
  •  时光说笑
    2021-01-05 05:42

    looking at your result matrix

    result = [[ 1, 2,   3, 4,]
              [ 2, 4,   6, 8,]
              [ 4, 8,  12, 16,]
              [ 8, 16, 24, 32,]]
    

    it can be deconstructed into product(elem-wise) of two matrix as

    a = [[1, 2, 3, 4],
        [1, 2, 3, 4],
        [1, 2, 3, 4],
        [1, 2, 3, 4]]
    
    b = [[1, 1, 1, 1],
         [2, 2, 2, 2],
         [4, 4, 4, 4]
         [8, 8, 8, 8]]
    
    result = a * b
    

    you can calculate this type of operation using the meshgrid function

    aa, bb = np.meshgrid(np.array([1.0, 2.0, 3.0, 4.0]),
                         np.array([1.0, 2.0, 4.0, 8.0]))
    result = aa * bb
    

提交回复
热议问题