以下代码的矢量化有什么好处吗?

Is there any benefit to vectorization of following code?

for i=1:numResults
    tempStructure=struct;
    for j=1:options.numDates
        stringJ=num2str(j);
        [tempStructure.(['temp' stringJ]),tempStructure.(['tempHHI' stringJ])]=fillTemp(resultsStructure.(['results' stringJ]),resultsStructure.(['resultsHHI' stringJ]),options.resultSize,i);
    end
end

在这里,我们可以假设 resultStructure 在循环之前有字段(动态指定)并且每个字段都存在于 resultStructure.

fillTemp 是一个很难向量化的复杂函数。

通过上面代码中的 bsxfun 删除 ij 的 "for" 循环以提高性能有什么好处吗?也欢迎任何加速上述代码的替代方法。

注意:我理解我定义和使用具有动态场的结构的方式不是最佳解决方案,但这是一个可行的解决方案,我不想修改工作解决方案。

我正在使用 MATLAB R2018a。

看来您在这里问错了问题,原因如下:您的 objective 似乎在整体上提高了代码的性能,但出于某些未指明的原因,您决定这样做专注于特定部分,并尝试对其应用bsxfun。根据此信息,您似乎面临着所谓的 an XY problem.

了解矢量化固然很好,但您应该记住它只是可用于此目的的众多技术之一(事实上 there's a whole book about it). Why, for example, did you not consider parfor, or mex?

程序员中有句名言是“过早的优化是万恶之源”。实际上,这意味着您应该首先确定程序中的瓶颈,然后考虑如何解决它们。第一部分可以使用 profiler (example and additional explanation here). The second part depends on the specifics of your code (which are not sufficiently detailed in your question, see also: How to create a Minimal, Reproducible Example) 来完成,所以很遗憾,这里不能给出一个笼统的答案。

如之前的评论所述,矢量化的好处可能是提高性能,并且在可能的情况下,代码会变得更短、可读性更好并降低出现错误的可能性(即,较长的代码往往会产生更多的错误,对于constant "bugs per line-of-code").

P.S.
由于您提到您使用 R2018a,因此由于 implicit expansion.

的引入,甚至不再需要 bsxfun