【发布时间】:2014-08-25 14:27:41
【问题描述】:
假设您有 5 个向量:v_1、v_2、v_3、v_4 和 v_5。这些向量中的每一个都包含从最小值到最大值的一系列值。比如:
v_1 = minimum_value:step:maximum_value;
这些向量中的每一个都使用相同的步长,但具有不同的最小值和最大值。因此它们的长度各不相同。
函数 F(v_1, v_2, v_3, v_4, v_5) 依赖于这些向量,并且可以使用其中元素的任意组合。 (为糟糕的解释道歉)。我试图找到 F 的最大值并记录导致它的值。我目前的方法是使用多个嵌入式 for 循环,如图所示为向量元素的每个组合计算出函数:
% Set the temp value to a small value
temp = 0;
% For every combination of the five vectors use the equation. If the result
% is greater than the one calculated previously, store it along with the values
% (postitions) of elements within the vectors
for a=1:length(v_1)
for b=1:length(v_2)
for c=1:length(v_3)
for d=1:length(v_4)
for e=1:length(v_5)
% The function is a combination of trigonometrics, summations,
% multiplications etc..
Result = F(v_1(a), v_2(b), v_3(c), v_4(d), v_5(e))
% If the value of Result is greater that the previous value,
% store it and record the values of 'a','b','c','d' and 'e'
if Result > temp;
temp = Result;
f = a;
g = b;
h = c;
i = d;
j = e;
end
end
end
end
end
end
对于小步长,这会变得非常慢。如果每个向量中有大约 100 个元素,则组合数约为 100*100*100*100*100。这是一个问题,因为我需要小步长值来获得适当收敛的答案。
我想知道是否可以使用Vectorization 或任何其他方法来加快速度。在计算之前我也在查看generating the combinations,但这似乎比我目前的方法还要慢。我已经很久没有使用 Matlab 了,但是仅仅看一下嵌入式 for 循环的数量就让我觉得这绝对可以加快速度。谢谢你的建议。
【问题讨论】:
-
你需要向量化
F本身。 -
您能详细说明一下吗?据我了解 - 这将涉及消除 for 循环并将 a、b、c、d 和 e 作为向量编写。当我只想要最大值时,矢量化 F 将涉及创建一个巨大的数组。这会更快吗?
-
您将这些向量中的每个元素提供给
F,因此要真正向量化您的问题,您需要修改Fs.t.它接受整个向量并与它们一起工作。向我们透露F可能会使我们处于更好的位置来评估矢量化它的可能性。
标签: matlab for-loop performance cpu-speed