I have a large vector field, where the field is large (e.g. 512^3; but not necessarily square) and the vectors are either 2D or 3D (e.g. shapes are [512, 512, 512, 2] or [512, 512, 512, 3]).
What is the fastest way to compute a scalar field of the squared-magnitude of the vectors?
I could just loop over each direction, i.e.
import numpy as np
shp = [256,256,256,3] # Shape of vector field
vf = np.arange(3*(256**3)).reshape(shp) # Create vector field
sf = np.zeros(shp[:3]) # Create scalar field for result
for ii in range(shp[0]):
for jj in range(shp[1]):
for kk in range(shp[2]):
sf[ii,jj,kk] = np.dot( vf[ii,jj,kk,:] , vf[ii,jj,kk,:] )
but that is fairly slow, is there anything faster?