0

I am trying to fill an array with calculated values from functions defined earlier in my code. I started with a code that has a similar structure to the following:

from numpy import cos, sin, arange, zeros

a = arange(1000)
b = arange(1000)


def defcos(x):
    return cos(x)


def defsin(x):
    return sin(x)

a_len = len(a)
b_len = len(b)

result = zeros((a_len,b_len))



for i in xrange(b_len):
    for j in xrange(a_len):
        a_res = defcos(a[j])
        b_res = defsin(b[i])

        result[i,j] = a_res * b_res

I tried to use array representations of the functions, which ended up in the following change for the loop

a_res = defsin(a)
b_res = defcos(b)

for i in xrange(b_len):
    for j in xrange(a_len):
        result[i,j] = a_res[i] * b_res[j]

This is already significantly faster, than the first version. But is there a way to avoid the loop entirely? I have encountered those loops a couple of times in the past but never botheres as it was not critical in terms of speed. But this time it is the core component of something, which is looped through a couple of times more. :)

Any help would be appreciated, thanks in advance!

1 Answer 1

1

Like so:

from numpy import newaxis

a_res = sin(a)
b_res = cos(b)

result = a_res[:, newaxis] * b_res

To understand how this works, have a look at the rules for array broadcasting. And please don't define useless functions like defsin, just use sin itself! Another minor detail, you get i from range(b_len), but you use it to index a_res! This is a bug if a_len != b_len.

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

1 Comment

Thanks, thats exactly what I was looking for. I thought there had to be a way but never found it. defsin(x) and defcos(x) should only show, that there are actual function calls from that particular line. The functions I use are of course more complex than that.

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.