0

I have the following numpy array

u = np.array([a1,b1,a2,b2...,an,bn])

where I would like to subtract the a and b elements from each other and end up with a numpy array:

u_result = np.array([(a2-a1),(b2-b1),(a3-a2),(b3-b2),....,(an-a_(n-1)),(an-a_(n-1))])

How can I do this without too much array splitting and for loops? I'm using this in a larger loop so ideally, I would like to do this efficiently (and learn something new)

(I hope the indexing of the resulting array is clear)

4 Answers 4

2

Or simply, perform a substraction :

u = np.array([3, 2, 5, 3, 7, 8, 12, 28])
u[2:] - u[:-2]

Output:

array([ 2,  1,  2,  5,  5, 20])
Sign up to request clarification or add additional context in comments.

Comments

1

you can use ravel torearrange as your original vector.

Short answer:

u_r = np.ravel([np.diff(u[::2]), 
                np.diff(u[1::2])], 'F')

Here a long and moore detailed explanation:

  1. separate a from b in u this can be achieved indexing
  2. differentiate a and b you can use np.diff for easiness of code.
  3. ravel again the differentiated values.
#------- Create u---------------
import numpy as np

a_aux = np.array([50,49,47,43,39,34,28])
b_aux = np.array([1,2,3,4,5,6,7])

u = np.ravel([a_aux,b_aux],'F')
print(u)
#-------------------------------
#1)
# get a as elements with index 0, 2, 4 ....
a = u[::2]
b = u[1::2] #get b as 1,3,5,....
#2)
#differentiate
ad = np.diff(a)
bd = np.diff(b)
#3)
#ravel putting one of everyone
u_result = np.ravel([ad,bd],'F')

print(u_result)

1 Comment

Thank you, your answer produced the correct answer and was also the fastest among the correct suggestions
1

You can try in this way. Firstly, split all a and b elements using array[::2], array[1::2]. Finally, subtract from b to a (np.array(array[1::2] - array[::2])).

import numpy as np

array = np.array([7,8,9,6,5,2])

u_result = np.array(array[1::2] - array[::2] )
print(u_result)

Comments

1

Looks like you need to use np.roll:

shift = 2
u = np.array([1, 11, 2, 12, 3, 13, 4, 14])
shifted_u = np.roll(u, -shift)
(shifted_u - u)[:-shift]

Returns:

array([1, 1, 1, 1, 1, 1])

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.