gpt4 book ai didi

matlab - 为什么 trapz 积分的速度取决于输入值的大小?

转载 作者:行者123 更新时间:2023-12-02 06:58:28 25 4
gpt4 key购买 nike

我在 matlab 中的代码中有一个小错误,我从单个值(而不是数组)开始积分循环。

我注意到,如果我给出 trapz(1,1),它几乎立即给出零(对于 trapz(x,y) 应该如此),但是计算它所花费的时间很大程度上取决于“y”的大小.

即:

tic;trapz(5.1000,1.6610e+03);toc
Elapsed time is 0.011022 seconds.

tic;trapz(5.1000,1.6610e+04);toc
Elapsed time is 0.485286 seconds.

tic;trapz(5.1000,1.6610e+05);toc
Elapsed time is 46.400199 seconds.

tic;trapz(5.1000,1.6610e+06);toc
..Still going on

我对此没有任何解释。为什么输入的值很重要?

最佳答案

有两个标量输入,trapz将您的调用解释为

trapz(y,dim) integrates across dimension dim of y

为了沿着该维度进行积分,它使用 permute 应用排列。随着 dim 的增加,这种排列的成本会更高。这些是 trapz 代码的相关行:

perm = [dim:max(ndims(y),dim) 1:dim-1];
y = permute(y,perm);

尝试自己计时:

>> y = 5; dim = 1e3;
tic, perm = [dim:max(ndims(y),dim) 1:dim-1]; y = permute(y,perm); toc
Elapsed time is 0.001761 seconds.

>> y = 5; dim = 1e4;
tic, perm = [dim:max(ndims(y),dim) 1:dim-1]; y = permute(y,perm); toc
Elapsed time is 0.148300 seconds.

>> y = 5; dim = 1e5;
tic, perm = [dim:max(ndims(y),dim) 1:dim-1]; y = permute(y,perm); toc
Elapsed time is 17.534308 seconds.

关于matlab - 为什么 trapz 积分的速度取决于输入值的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42983643/

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