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.

4

2 回答 2

5

我知道,实际上并没有相当于 bsxfun 的东西,尽管 numpy 确实为你处理了很多广播,正如其他人提到的那样。

这通常被吹捧为 numpy 优于 matlab 的一个优势,确实很多广播在 numpy 中更简单,但 bsxfun 实际上更通用,因为它可以接受用户定义的函数。

Numpy 有这个: http ://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html 但仅适用于 1d。

于 2014-10-17T02:38:53.850 回答
2

与 matlab bsxfun(x) 相比,Python 非常易于使用 python numpy 中的 ... in array[] 可以轻松完成,例如 m[...,:] 你可以试试这个:

>>>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.]]
于 2017-07-21T14:01:07.297 回答