简体   繁体   中英

Broadcasting a M*D matrix to N*D matrix in python (D is greater than 1, M>N)

I would like to subtract the rows of a MXD matrix from a NXD matrix (D is greater than 1, M > N) without using any for loops in Python. eg suppose I want to subtract the rows of a 100*25 matrix from the rows of a 20*25 matrix. How to write the code without for loops (I know I can do it using broadcasting but can't seem to code).

Method 1:

def subtract(A, B):
    m = A.shape[0]
    n = B.shape[0]
    C = np.empty_like(A)

    for i in range(m // n):
        C[i*n : (i+1)*n] = A[i*n : (i+1)*n] - B

    return C

Method 2:

def subtract(A, B):
    m = A.shape[0]
    n = B.shape[0]
    return A - np.tile(B, (m // n, 1))

Method 3:

def subtract(A, B):
    B_ = np.repeat(B, 5).reshape(B.size, -1).T.reshape(-1, B.shape[1])
    return A - B_

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM