【问题标题】:Matlab: How to compare the progressive value of a variable to it's previous best and reassign it to it's previous best?Matlab:如何将变量的渐进值与其以前的最佳值进行比较并将其重新分配给以前的最佳值?
【发布时间】:2016-09-23 03:01:01
【问题描述】:

我有一段代码可以在循环中评估变量的性能,这样我们就可以检查它的进度并将其与它的最佳值进行比较,如果新分配的值是,则将其分配回这个最佳值评估为不优于此变量在其最佳值时的性能。

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 变量会一遍又一遍地更改它。到目前为止,这段代码没有给出预期的结果,其余代码不需要任何更改。

【问题讨论】:

  • 假设你已经在循环外初始化了w=A 和wbest=B。在第一次迭代结束时,您将始终拥有w = wbest (== A or B)。因此,在第二次迭代中,您将始终拥有err == err_best,然后您将再次拥有wbest = w (==A or B),然后是w = wbest (==A or B)。所以你的迭代只是不断循环,但什么也不做。此外,您可能需要重新考虑您的算法。 “将其分配回这个最佳值”意味着您将简单地返回到先前的计算步骤。除非您的算法第二次以不同的方式执行该步骤,否则这将无济于事。
  • 如果您想要一个真正快速的解决方案,我们需要一个具有您所需输出的示例数据集。
  • @MingjingZhang 有代码更改 w 值,但未显示,因此在第二次迭代中会出现不同的错误。
  • 你为什么要在最后做 w=wbest?新的 w 是否依赖于旧的 w?如果是这样,并且下一个 w 给出的错误比最好的差,那么你的算法就会卡住。
  • 我解决了。感谢所有指出这段代码冗余的人。我删除了最后一个命令,并以不同的方式使用了 wbest,所以我得到了预期的结果。我很感激。命令 w = wbest;已经相当昂贵了。特别感谢@MingjingZhang

标签: matlab loops if-statement for-loop


【解决方案1】:

您始终可以在 wbest 中附加最佳值,并将 wbest(end) 用作“迄今为止最佳”,例如:

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 的历史记录。

【讨论】:

  • 这种方法也不能解决问题。不过谢谢。如果您在问题中附加的代码中发现任何错误,您能否指出?谢谢
  • 在否决试图免费帮助您的人之前,您能否详细说明“不能解决问题”? w是什么形状的
  • 我从不投反对票。我使用您的方法得到的结果与使用帖子中附加的代码相同。我更想知道我在代码中的方法是否有任何问题。谢谢。
猜你喜欢
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 2022-06-25
  • 2021-11-19
  • 2017-09-17
  • 1970-01-01
相关资源
最近更新 更多