[Numpy-discussion] Efficiently defining a multidimensional array
Thu Aug 27 16:52:34 CDT 2009
This isn't quite your typical linear algebra. NumPy has a nice feature
called array broadcasting, which enables you to perform element-wise
operations on arrays of different shapes. The number of dimensions of
the arrays must be the same, in your case, all the arrays must have
three dimensions. The newaxis keyword is useful for creating a
dimension of size one.
import numpy as np
# Line up the axes of size>1 by creating a new axis for each array.
C=A[:,:,np.newaxis] + B[np.newaxis,:,:]
# This is equivalent to the much slower triple for-loop
for x in xrange(0,m):
for y in xrange(0,n):
for z in xrange(0,k):
# This should be true.
I hope this helps.
On Thu, Aug 27, 2009 at 3:09 PM, Jonathan T<firstname.lastname@example.org> wrote:
> I want to define a 3-D array as the sum of two 2-D arrays as follows:
> C[x,y,z] := A[x,y] + B[x,z]
> My linear algebra is a bit rusty; is there a good way to do this that does not
> require me to loop over x,y,z? Thanks!
> NumPy-Discussion mailing list
Damian Eads Ph.D. Candidate
University of California Computer Science
1156 High Street Machine Learning Lab, E2-489
Santa Cruz, CA 95064 http://www.soe.ucsc.edu/~eads
More information about the NumPy-Discussion