1

I have a 2D numpy array, A.

I want to subtract each rows, one by one, from A, and store the row-wise absolute sum in an array.

Is there a way to carry out the operation without using the for loop ? Below is the code with for loop.

import numpy as np
A = np.random.randint(5,size=(8,9))
b = np.zeros(A.shape[1]);
for i in xrange(A.shape[0]):
    b = b + np.sum(np.absolute(A - A[i,:]), axis=0)

1 Answer 1

1

You could use broadcasting -

(np.abs(A[:,None,:] - A)).sum(axis=(0,1))

Steps :

(1) Keeping the last axis aligned get two versions of A :

Input1 (A[:,None,:])    :  M x 1 x N
Input2 (A)              :      M x N

Get the absolution differences between these two inputs resulting in a 3D array.

(2) Sum along the first two axes for final output.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.