[SciPy-user] Efficiently scaling matrix rows

eric jones eric at enthought.com
Tue Nov 29 12:40:46 CST 2005


Here is a snippet that does what you want.  The key is to use 
"broadcasting."  Here we take the 1D scale, and turn it into a Nx1 array.

Travis has some discussion of broadcasting here:

    http://www.tramy.us/scipybooksample.pdf

I also wrote a paper for pyzine a while back about broadcasting, but I 
don't have a copy available on this machine.  I'll try to scare it up 
and pass it on to you.

eric


from scipy import *

N = 5.0
a = ones((N,3),typecode=Float32)
print a

scale = arange(N)
print scale

b = a * scale[:,NewAxis]
print b

Neilen Marais wrote:

>Hi
>
>I have a an n x 3 matrix (i.e. each row contains three elements). I want
>to scale each row by the element of a 1-d array. I.o.w, if I have 
>
>arr = array([1., 2., 3., ....]),
>
>I want to scale the first row of the matrix by arr[0], the second by
>arr[1], etc. ATM I'm doing this:
>
>coefs = reshape(repeat(arr, 3), (-1, 3))
>mat = coefs*mat
>
>Is there a more efficent (and potentially easier to read) way that does
>not require redundant copies of arr, while avoiding a slow python loop?
>
>Thanks
>Neilen
>
>_______________________________________________
>SciPy-user mailing list
>SciPy-user at scipy.net
>http://www.scipy.net/mailman/listinfo/scipy-user
>  
>



More information about the SciPy-user mailing list