假设我有以下函数:
function x = printAndKeepX(x, y)
x
y
end
我调用bsxfun
像这样:
bsxfun(@printAndKeepX, 1:4, 1);
Were bsxfun
真的逐个元素,我希望printAndKeepX
被调用 4 次,并带有参数(x, y)
being (1, 1)
, (2, 1)
, (3, 1)
and (4, 1)
, 分别。但输出显示它仅被调用一次(x, y)
being ([1 2 3 4], 1)
:
x =
1 2 3 4
y =
1
为什么?我如何知道什么被视为“元素”?
Edit:
文档表明有时被调用的函数可以接收两个标量,有时可以接收一个向量/矩阵和一个标量。我可以确定会发生哪些情况吗?
我对常规版本和 GPU 版本都感兴趣bsxfun
.
The 文档还指出:
fun
还必须支持标量扩展,这样如果A
or B
是一个标量,C
是将标量应用于另一个输入数组中的每个元素的结果。
在你的情况下B
实际上是一个标量,所以你的函数应用于A
只有一次。
The same applies when the input arrays are matrices. For example, consider a case where bsxfun
is invoked with a matrix A
={ aij } of size m×n and a vector B
={ bij } of size m×1. B
would be replicated n times along the second dimension, and the function would be called as follows:
function([a11, ..., a1n], b1)
function([a21, ..., a2n], b2)
...
function([am1, ..., amn], bm)
这会导致 n 个函数调用矢量标量输入,而不是 mn 个函数调用标量对。如果函数被矢量化,则可能会体现出可能显着的性能增益。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)