2

How to optimize functions involving numpy arrays?

Use case:

def create_array_and_fill(a, b, N):
    res = np.zeros(N, N)

    res[0] = a
    res[-1] = b

    return res

c = create_array_and_fill(5, 9, 100)

But then, sometimes, I know beforehand the maximum size of all arrays that I need to use (say for testing purposes), so what's the best way to go? Should I preallocate and what is the best way to do so? For example, can I pass a preallocated array to a function so that the function just updates it instead of returning a new one?

My first ideas is as follows but, of course, it comes with a cost, I have to change all my function signatures now.

def create_array_and_fill(a, b, N, res):

    res[0] = a
    res[-1] = b

    # No more return here?

c = np.zeros(N, N)
create_array_and_fill(a, b, N, c) 
2
  • 2
    It depends on the function. You can pass a preallocated array to a function if that function is set up to allow passing a preallocated array. You'd need to be more specific to get a more specific answer. Commented Mar 3, 2013 at 1:06
  • I can change the function signature if need be, but how do I do that? Commented Mar 3, 2013 at 1:39

1 Answer 1

2

If I understand what you're asking, you could do something like this:

def fill_array(a, b, N, out=None):
    if out is None:
        out = np.zeros(N, N)
    out[0] = a
    out[-1] = b
    return out

This modifies the out object if one is provided, or returns a new one if no out is provided. In this case it still returns the value even if modifying an existing one, but you could easily modify it to return None instead if an expl;icit out was provided.

But yes, you're going to have to change your functions if you want them to work either way (with a given "out" array or by creating a new array). If you wrote code in a function that creates a new array, there's no magical way to make it not execute that code just because you have another array pre-created. You have to edit your function.

Sign up to request clarification or add additional context in comments.

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.