Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate numpy array based on cell indices

Tags:

python

numpy

I am trying to create a 3d-array, whose cell entries are to be calculated from the cell indices. Specifically, I want that cell (i,j,k) = sqrt(i+j+k).

This is very easily done with the following for loops:

N=10
A=np.zeros((N,N,N))

for i in range(N):
    for j in range(N):
        for k in range(N):
            A[i][j][k] = np.sqrt(i+j+k)

I was wondering if numpy has inbuilt functions that make these nested for loops redundant.

like image 995
Douglas James Bock Avatar asked Jun 05 '26 00:06

Douglas James Bock


1 Answers

Simplest and performant one would be with open grids using np.ogrid and then performing the relevant operation(s) -

I,J,K = np.ogrid[:N,:N,:N]
A = np.sqrt(I+J+K)

Or with np.sum for the broadcasted summations of open grids for a one-liner -

A = np.sqrt(np.sum(np.ogrid[:N,:N,:N]))

Relevant : General workflow on vectorizing loops involving range iterators.

like image 167
Divakar Avatar answered Jun 07 '26 13:06

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!