I would like to use vectorized operations for efficient code, where I do operations on arrays of different size such that slicing the arrays is necessary. However, I would like to adjust the function such that I can do calculations with flat numpy arrays as well with such having n rows. I have used simple numbers in this example, but will use random number generation in my project. Currently I have resolved it using an if statement to differentiate between slicing depending on shape. Is there a more efficient way without if statements?
import numpy as np
def func(a, b, c, d):
if len(a.shape) == 1:
cf = -c
cf[:len(b)] += a - b
cf[-len(d)] -= d
else:
cf = -c
cf[:, :b.shape[1]] += a - b
cf[:, -d.shape[1]:] -= d
return cf
a = np.array([1, 1, 1, 1, 1, 1, 1])
b = np.array([2, 2, 2, 2, 2, 2, 2])
c = np.array([3, 3, 3, 3, 3, 3, 3, 3])
d = np.array([4])
func(a, b, c, d)
n = 10
a = np.zeros((n, 7))+1
b = np.zeros((n, 7))+2
c = np.zeros((n, 8))+3
d = np.zeros((n, 1))+4
func(a, b, c, d)
It might be that I just did not find a universal method of slicing here?!