gpt4 book ai didi

performance - 我可以使这个 if else 语句更有效率吗

转载 作者:太空宇宙 更新时间:2023-11-03 20:11:09 24 4
gpt4 key购买 nike

有人想过比下面的 if else 函数更有效的解决方案吗?这占用了代码的大部分时间,因此我需要减少它。

完整的功能是

     function result = vre(t,r,e,n,d)
if (e==4 && r>0)
result = 0;
elseif (e==4 && r==0)
result = 1;
elseif (e<4 && r==1)
result = t;
elseif (e<4 && r==2)
result = d;
else
result=n;
end
end

最佳答案

如果此函数占用了您的大部分处理时间,几乎可以肯定是因为您调用它的次数过多。反过来,这很可能是因为您在向量或矩阵的每个元素上单独调用它。我建议更改函数以接受 er 的矩阵输入,这样您就可以一次执行所有检查 - matlab 是为矩阵构建的操作,因此利用这些始终是一个好主意。

function result = vre(t,r,e,n,d)
#% add error checking for size of input args if desired
result = ones(size(e))*n; #% default result; next assign special cases
result(e==4 & r>0) = 0; #% note the single & for element-wise 'and'
result(e==4 & r==0) = 1;
result(e<4 & r==1) = t;
result(e<4 & r==2) = d;

end

该函数现在返回一个与输入矩阵大小相同的矩阵 - 对于单个元素,它的工作方式与您当前的版本完全相同,但对于更高维的输入,它也可以工作,并且可能会给您带来可观的速度提升。

关于performance - 我可以使这个 if else 语句更有效率吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696463/

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