0

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?!

1 Answer 1

5

This code works.

def func(a, b, c, d):
    cf = -c
    cf[..., :b.shape[-1]] += a - b
    cf[..., -d.shape[-1]:] -= d
    return cf

Testing:

## Test 1
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)
"""
array([-4, -4, -4, -4, -4, -4, -4, -7])
"""

## Test 2
n = 2
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)
"""
array([[-4., -4., -4., -4., -4., -4., -4., -7.],
       [-4., -4., -4., -4., -4., -4., -4., -7.]])
"""
Sign up to request clarification or add additional context in comments.

4 Comments

Works great, thanks! Can you give a short explanation what the ... are for?
x[...,-1] : Ellipsis(...) expand to the number of : objects needed to make a selection tuple of the same length as x.ndim.
Thank you! Is the function written in the most efficient way?
I don't know what is the most efficient. You can improve it as your hope.

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.