[Numpy-discussion] Efficiently defining a multidimensional array

Damian Eads eads@soe.ucsc....
Thu Aug 27 16:52:34 CDT 2009


Hi Jonathan,

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

A=np.random.rand(m,n)
B=np.random.rand(n,k)

# 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
TC=np.zeros((m,n,k))
for x in xrange(0,m):
    for y in xrange(0,n):
        for z in xrange(0,k):
             TC[x,y,z]=A[x,y]+B[y,z]

# This should be true.
print (TC==C).all()

I hope this helps.

Damian

On Thu, Aug 27, 2009 at 3:09 PM, Jonathan T<terhorst@gmail.com> wrote:
> Hi,
>
> 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!
>
> Jonathan
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>



-- 
-----------------------------------------------------
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 mailing list