bsxfun是否真的在元素上应用了? [英] Is bsxfun really applied element-wise?
问题描述
假设我具有以下功能:
function x = printAndKeepX(x, y)
x
y
end
,我像这样调用bsxfun
:
bsxfun(@printAndKeepX, 1:4, 1);
实际上是逐个元素,我希望printAndKeepX
被调用4次,而(x, y)
的参数分别是(1, 1)
,(2, 1)
,(3, 1)
和(4, 1)
.但是输出显示,仅在(x, y)
为([1 2 3 4], 1)
的情况下调用了它一次:
Were bsxfun
really element-by-element, I would expect printAndKeepX
to be called 4 times, with the arguments (x, y)
being (1, 1)
, (2, 1)
, (3, 1)
and (4, 1)
, respectively. But the output shows that it is called just once with (x, y)
being ([1 2 3 4], 1)
:
x =
1 2 3 4
y =
1
为什么?我怎么知道什么被认为是元素"?
Why? How can I know what's considered an "element"?
修改:
文档建议,有时被调用函数可以接收两个标量,有时一个可以接收一个标量.向量/矩阵和标量.我能确定哪些会发生吗?
The documentation suggests that sometimes the called function can receive two scalars and sometimes a vector/matrix and a scalar. Can I know for sure which of these is going to happen?
我对bsxfun
的常规版本和GPU版本都感兴趣.
I'm interested in both the regular and GPU versions of bsxfun
.
推荐答案
文档还指出:
fun
还必须支持标量扩展,例如,如果A
或B
是标量,则C
是将标量应用于其他输入数组中的每个元素的结果.
fun
must also support scalar expansion, such that ifA
orB
is a scalar,C
is the result of applying the scalar to every element in the other input array.
在您的情况下B
实际上是标量,因此您的函数仅在A
上应用一次.
In your case B
is in fact a scalar, so your function is applied on A
only once.
当输入数组是矩阵时,也是如此.例如,考虑使用大小为 m ×A = { a ij }调用bsxfun
的情况> n 和大小为 m ×1的向量B
= { b ij }. B
将沿第二维复制 n 次,该函数的调用方式如下:
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)
function([a11, ..., a1n], b1)
function([a21, ..., a2n], b2)
...
function([am1, ..., amn], bm)
这将导致对向量标量输入的 n 函数调用,而不是对成对的标量的 mn 函数调用.如果将该函数向量化,则可能会显着提高性能.
This results in n function calls for vector-scalar inputs rather then mn function calls for pairs of scalars. If the function is vectorized, it may be reflected in a possibly significant performance gain.
这篇关于bsxfun是否真的在元素上应用了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!