[Numpy-discussion] matrix division without a loop
peridot.faceted at gmail.com
Fri Mar 12 16:54:29 EST 2010
On 12 March 2010 13:54, gerardo.berbeglia <gberbeglia at gmail.com> wrote:
> I want to "divide" an n x n (2-dimension) numpy array matrix A by a n
> (1-dimension) array d as follows:
Look up "broadcasting" in the numpy docs. The short version is this:
operations like division act elementwise on arrays of the same shape.
If two arrays' shapes differ, but only in that one has a 1 where the
other has an n, the one whose dimension is 1 will be effectively
"repeated" n times along that axis so they match. Finally, if two
arrays have shapes of different lengths, the shorter is extended by
prepending as many dimensions of size one as necessary, then the
previous rules are applied.
Put this together with the ability to add "extra" dimensions of length
1 to an array by indexing with np.newaxis, and your problem becomes
In : A = np.array([[1,2],[3,4]]); B = np.array([1.,2.])
In : A.shape
Out: (2, 2)
In : B.shape
In : A/B
array([[ 1., 1.],
[ 3., 2.]])
In : A/B[:,np.newaxis]
array([[ 1. , 2. ],
[ 1.5, 2. ]])
If you're using matrices, don't. Stick to arrays.
> Take n = 2.
> Let A= 2 3
> 1 10
> and let d = [ 3 2 ]
> Then i would like to have "A/d" = 2/3 3/3
> 1/2 10/2
> This is to avoid loops to improve the speed.
> Thank you in advance!
> View this message in context: http://old.nabble.com/matrix-division-without-a-loop-tp27881350p27881350.html
> Sent from the Numpy-discussion mailing list archive at Nabble.com.
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
More information about the NumPy-Discussion