[Numpy-discussion] matrix division without a loop
Anne Archibald
peridot.faceted@gmail....
Fri Mar 12 15:54:29 CST 2010
On 12 March 2010 13:54, gerardo.berbeglia <gberbeglia@gmail.com> wrote:
>
> Hello,
>
> 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
simple:
In [13]: A = np.array([[1,2],[3,4]]); B = np.array([1.,2.])
In [14]: A.shape
Out[14]: (2, 2)
In [15]: B.shape
Out[15]: (2,)
In [16]: A/B
Out[16]:
array([[ 1., 1.],
[ 3., 2.]])
In [17]: A/B[:,np.newaxis]
Out[17]:
array([[ 1. , 2. ],
[ 1.5, 2. ]])
If you're using matrices, don't. Stick to arrays.
Anne
> 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@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
More information about the NumPy-Discussion
mailing list