Reputation: 347
Suppose I have a m x n numpy array:
([[4,6,7],[5,2,1],[5,6,7],[5,3,5]])
And I want to perform an operation with every row and its proceeding row. How can this be done without a for-loop? The specific operation here computes the unit vector between two successive rows in this array. For example,
# Row 1 would be:
[5,2,1]-[4,6,7]/norm([5,2,1]-[4,6,7])
# Row 2 would be
[5,6,7]-[5,2,1]/norm([5,6,7]-[5,2,1])
and so on... yielding a 3x3 numpy array
Upvotes: 1
Views: 40
Reputation: 9047
Get the difference and divide by norm
arr = np.array([[4,6,7],[5,2,1],[5,6,7],[5,3,5]])
op = arr[1:] - arr[:-1]
op = op/np.linalg.norm(op, ord=2, axis=1, keepdims=True)
print(op)
[[ 0.13736056 -0.54944226 -0.82416338]
[ 0. 0.5547002 0.83205029]
[ 0. -0.83205029 -0.5547002 ]]
Upvotes: 2