简体   繁体   中英

Is is possible each cell of a numpy array iteratively from a function?

Was not sure how exactly to word the question but here is the problem:

I essentially have an empty array S that is of shape n * n. I also have an array of data R, of shape n * m. My goal is for S[i][j] = some func combining R[i] R[j].

This is the code I wrote to accomplish what I want:

for i in range(n):
    for j in range(n):
        S[i][j] = foo(R[i], R[j])

I'd like to know if there is an existing numpy function that can do something like this, so I do not have to write the for loops.

In numpy we generally write foo to to be "array aware" to avoid needing to loop over our inputs. For example, you could take this function crossAddF and write an array aware version crossAddArray :

def crossAdd(a, b):
    S = np.zeros([len(a), len(b)])
    for i in range(len(a)):
        for j in range(len(b)):
            S[i][j] = a[i] + b[j]
    return S

def corssAddArray(a, b):
    a = np.reshape(a, [len(a), 1])
    b = np.reshape(b, [1, len(b)])
    return a + b

That being said, I realize that we sometimes need to work with functions that weren't meant for numpy that we can't easily re-write or change. In that case numpy.vectorize can be useful. Keep in mind that vectorize can be slower than other implementations of the same functionality. Here's an example:

def foo(i, j):
    return float(i) + float(j)

def crossAddUsingVectorize(a, b):
    a = np.reshape(a, [len(a), 1])
    b = np.reshape(b, [1, len(b)])
    return np.vectorize(foo)(a, b)

My examples also use numpy's broadcasting feature it might be worth reading about if you're not already familiar with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM