1

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

1
  • data[1:,:]-data[:-1,:] gives the difference between successive rows. Commented Feb 19, 2021 at 6:20

1 Answer 1

2

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 ]]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.