23

I'm trying to port some of my code from matlab to python, and some of it uses the bsxfun() function for virtual replication followed by multiplication or division (I also use it for logical operations). I'd like to be able to do this without actually replicating the vector (either with a function or with some kind of diagonal matrix) before multiplying or dividing to save on memory and time.

If there's an equivalent of bsxfun in a C library of some kind, that would of course also work.

Shai
  • 111,146
  • 38
  • 238
  • 371
Kevin
  • 343
  • 1
  • 3
  • 9
  • 6
    If you're working with arrays in Python you're going to want to be using numpy (www.numpy.org), and numpy has very nice broadcasting properties. (See http://www.scipy.org/EricsBroadcastingDoc for a short tutorial.) – DSM Jan 20 '12 at 19:34
  • 2
    According to this [question](http://stackoverflow.com/questions/3213212/matlab-equivalent-of-numpy-broadcasting) the equivalent of numpy broadcasting in matlab is `bsxfun`, so I guess this works the other way around. – jcollado Jan 20 '12 at 19:45
  • 1
    There is now an "official" numpy broadcasting tutorial at http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html The tutorial suggested by DSM can still be found at https://github.com/dwf/rescued-scipy-wiki/blob/master/EricsBroadcastingDoc.rst – user2809402 Nov 02 '13 at 19:28

2 Answers2

6

There isn't really an equivalent of bsxfun, that I'm aware of, although numpy does take care of a lot of broadcasting for you, as others mentioned.

This is commonly touted as an advantage of numpy over matlab, and it is true that a lot of broadcasting is simpler in numpy, but bsxfun is actually more general, because it can take user-defined functions.

Numpy has this: http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html but only for 1d.

capybaralet
  • 1,757
  • 3
  • 21
  • 31
3

Python is very easy to use compared to matlab bsxfun(x) in python numpy can be easily done by ... in array[], e.g. m[...,:] You can try this:

>>>m = np.zeros([5,13], dtype=np.float32)
>>>print(m)

    [[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
     [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
     [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
     [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
     [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]

>>>c=np.array([[1,2,3,4,5,6,7,8,9,10,11,12,13]])
>>>print(m[...,:] +4*c)
[[  4.   8.  12.  16.  20.  24.  28.  32.  36.  40.  44.  48.  52.]
 [  4.   8.  12.  16.  20.  24.  28.  32.  36.  40.  44.  48.  52.]
 [  4.   8.  12.  16.  20.  24.  28.  32.  36.  40.  44.  48.  52.]
 [  4.   8.  12.  16.  20.  24.  28.  32.  36.  40.  44.  48.  52.]
 [  4.   8.  12.  16.  20.  24.  28.  32.  36.  40.  44.  48.  52.]]
CCT
  • 29
  • 4