我有一段代码来评估循环中变量的性能,以便我们不断检查其进度并将其与它的最佳值进行比较并将其分配回最佳值如果新分配的值被评估为不比该变量的最佳值的性能好。
for (True)
err = sum(Y*X'*w <=0); %measure the performance of w for fixed X and Y variables.
err_best = sum(Y*X'*wbest <=0); %measure the performance of w best
if(err <= err_best) %if performance of newly assigned value of w is better than that of its career best wbest then update wbest with this newly identified best value.
wbest = w; %update the value of wbest if the w is evaluated to be better than the previous best wbest.
end
w = wbest; % wbest is updated to the best value evaluated thus far and assign to w this value.
% Code to change w value.
end
请忽略其余代码,因为这对于这个问题并不重要。我想知道如何保留变量w的最佳值并将其存储在wbest中,因为w变量通过代码一遍又一遍地改变它。截至目前,这段代码并未按预期提供结果,其余代码也不需要任何更改。
答案 0 :(得分:-1)
您始终可以在wbest
中添加最佳值,并使用wbest(end)
作为“最佳”,直到现在为止#39}。像:
for (True)
err = sum(Y*X'*w <=0); %measure the performance of w for fixed X and Y variables.
err_best = sum(Y*X'*wbest(end) <=0); %measure the performance of w best
if(err <= err_best) %if performance of newly assigned value of w is better than that of its career best wbest then update wbest with this newly identified best value.
wbest = [wbest w]; %update the value of wbest if the w is evaluated to be better than the previous best wbest.
end
w = wbest(end); % wbest is updated to the best value evaluated thus far and assign to w this value.
% Code to change w value.
end
这将确保您在离开循环时有wbest
的历史记录。