gpt4 book ai didi

performance - Matlab bsxfun - 为什么 bsxfun 在这种情况下无法工作?

转载 作者:太空宇宙 更新时间:2023-11-03 19:55:21 26 4
gpt4 key购买 nike

我有一个二元函数,大致看起来像

func=@(i,j)exp(-32*(i-j)^2);

网格如下

[X Y]=meshgrid(-10:.1:10);

奇怪的是,arrayfun 会产生正确的结果,而 bsxfun 会产生 Inf 的条目。

an1=arrayfun(func,X,Y);
an2=bsxfun(func,X,Y);

>> max(max(abs(an1-an2)))
ans =
Inf

为什么?


编辑:现在问题已解决。我包含了一些基准数据,以促进关于 bsxfun

效率的讨论

假设网格已经生成

[X Y]=meshgrid(Grid.partition);
func=@(i,j)exp(-32*(i-j).^2);

(我打算在不同的地方多次重复使用网格。)

为嵌套命名函数方法计时。

>> tic;for i=1:1000;temp3=exp(-32*bsxfun(@minus,Grid.partition.',Grid.partition).^2);end;toc,clear temp
Elapsed time is 1.473543 seconds.
>> tic;for i=1:1000;temp3=exp(-32*bsxfun(@minus,Grid.partition.',Grid.partition).^2);end;toc,clear temp
Elapsed time is 1.497116 seconds.
>> tic;for i=1:1000;temp3=exp(-32*bsxfun(@minus,Grid.partition.',Grid.partition).^2);end;toc,clear temp
Elapsed time is 1.816970 seconds.

计时匿名函数方法

>> tic;for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear temp
Elapsed time is 1.134980 seconds.
>> tic;for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear temp
Elapsed time is 1.171421 seconds.
>> tic;for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear temp
Elapsed time is 1.180998 seconds.

可以看出匿名函数方法比嵌套函数方法更快(不包括meshgrid上的时间)。

如果包含meshgrid上的时间,

>> tic;[X Y]=meshgrid(Grid.partition);for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear X Y temp
Elapsed time is 1.965701 seconds.
>> tic;[X Y]=meshgrid(Grid.partition);for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear X Y temp
Elapsed time is 1.249637 seconds.
>> tic;[X Y]=meshgrid(Grid.partition);for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear X Y temp
Elapsed time is 1.208296 seconds.

很难说...

最佳答案

根据documentation , 当你用任意函数调用 bsxfunfunc,

funcmust be able to accept as input either two column vectors of the same size, or one column vector and one scalar, and return as output a column vector of the same size as the input(s).

您的功能无法实现。要更正它,请将 ^ 替换为 。^:

func=@(i,j)exp(-32*(i-j).^2);

无论如何,您可以使用 bsxfun 的内置函数之一代替您的函数(参见 @Divakar's answer)。这样你就可以避免 meshgrid,而且代码可能会更快。

关于performance - Matlab bsxfun - 为什么 bsxfun 在这种情况下无法工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28626474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com