Is there an equivalent to the MATLAB function bsxfun in python?

后端 未结 2 2038
执笔经年
执笔经年 2020-12-31 00:32

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 u

相关标签:
2条回答
  • 2020-12-31 01:05

    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.

    0 讨论(0)
  • 2020-12-31 01:07

    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.]]
    
    0 讨论(0)
提交回复
热议问题