gpt4 book ai didi

octave - 使用 arrayfun 将函数的两个参数应用于每个组合

转载 作者:行者123 更新时间:2023-12-02 05:43:43 26 4
gpt4 key购买 nike

i = [1 2]j = [3 5]。现在 Octave 音阶:

arrayfun(@(x,y) x+y,i,j)

我们得到[4 7]。但我想将该函数应用于 ij 的组合以获得 [i(1)+j(1) i(1)+j (2) i(2)+j(1) i(2)+j(2)]=[4 6 5 7]

我该如何实现这个目标?我知道我可以使用 for-loopsl,但我想要矢量化代码,因为它更快。

最佳答案

在 Octave 中,为了求两个向量之间的总和,您可以使用真正的向量化方法 broadcasting就像这样-

out = reshape(ii(:).' + jj(:),[],1)

这是对 ideone 的运行时测试对于每个大小为 1 x 100 的输入向量 -

-------------------- With FOR-LOOP
Elapsed time is 0.148444 seconds.
-------------------- With BROADCASTING
Elapsed time is 0.00038299 seconds.

如果您想让它保持通用以适应求和以外的操作,您可以使用像这样的匿名函数 -

func1 = @(I,J) I+J;
out = reshape(func1(ii,jj.'),1,[])
<小时/>

在 MATLAB 中,您可以使用两个 bsxfun 完成相同的任务接下来列出的替代方案。

我。 bsxfun 与匿名函数 -

func1 = @(I,J) I+J;
out = reshape(bsxfun(func1,ii(:).',jj(:)),1,[]);

二. bsxfun 带有内置 @plus -

out = reshape(bsxfun(@plus,ii(:).',jj(:)),1,[]);

对于每个大小为 1 x 10000 的输入向量,我最后的运行时间是 -

-------------------- With FOR-LOOP
Elapsed time is 1.193941 seconds.
-------------------- With BSXFUN ANONYMOUS
Elapsed time is 0.252825 seconds.
-------------------- With BSXFUN BUILTIN
Elapsed time is 0.215066 seconds.

关于octave - 使用 arrayfun 将函数的两个参数应用于每个组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152963/

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