Numpy Matrix Subtraction Confusion

前端 未结 2 1367
耶瑟儿~
耶瑟儿~ 2021-02-14 08:08

I have a question about the result of an operation I accidentally performed with two numpy matrices (and later fixed).

Let\'s say that I have a column vector, A = [1,2,

2条回答
  •  春和景丽
    2021-02-14 08:51

    A and B are being broadcasted together:

    A = np.matrix([[1],[2],[3]])
    #a 3x1 vector
    #1
    #2
    #3
    
    B = np.matrix([[1,1,1]])
    #a 1x3 vector
    #1 1 1
    
    A-B
    #a 3x3 vector
    #0 0 0
    #1 1 1
    #2 2 2
    

    A gets broadcasted along its size 1 dimension(columns) into

    #1 1 1
    #2 2 2
    #3 3 3
    

    B get broadcasted along its size 1 dimension(rows) into

    #1 1 1
    #1 1 1
    #1 1 1
    

    Then A-B is computed as usual for two 3x3 matrices.

    If you want to know why it does this instead of reporting an error it's because np.matrix inherits from np.array. np.matrix overrides multiplication, but not addition and subtraction, so it uses the operations based on the np.array, which broadcasts when the dimensions allow it.

提交回复
热议问题