Problem with how to select the best result from a loop calculation

1 回表示 (過去 30 日間)
zhe li
zhe li 2013 年 1 月 10 日
Dear All,
Thanks for your time.
I am currently writting a code. I would like to obtain the best solution after running a loop and then obtain the corresponding variables used. I will show a sample code such as:
for i=1:2
a(1)=2
a(2)=3
c=a.*3
end
b=min(c)
d=a(i)
The correct answer is b=6 and d=a(1).However, I can either get b=6 but d=a(3) or b=9 and d=a(2).
Could somebody help me with this please? Thank you very much.
Zhe Li
[EDITED, Jan, code formatted]
  2 件のコメント
Jan
Jan 2013 年 1 月 10 日
The contents of the FOR loop does not depend on the loop counter "i". So why do you use a loop? How can "d=a(3)" happen, when you define only a(1) and a(2)?
zhe li
zhe li 2013 年 1 月 10 日
Dear Jan,
Thanks for sending me the comments.
I only used this as an example. The actual code I am writting involved calling other functions instead of a(1) and a(2). This is the reason that I used 'for loop'. d=a(3) is not going happen as far as I am concerned, as the example showing, I would only expect two sets of calculation done.
Thanks again,
Zhe Li

サインインしてコメントする。

採用された回答

José-Luis
José-Luis 2013 年 1 月 10 日
編集済み: José-Luis 2013 年 1 月 10 日
the_best = bitmax; %largest possible value, Inf would work as well
for ii = 1:1000
your_new_min = %however you get it
if (your_new_min < the_best)
the_best = your_new_min;
b_best = %whatever the current value of b is
d_best = %whatever the current value of d is
end
end
  2 件のコメント
zhe li
zhe li 2013 年 1 月 10 日
Hi Jose-luis,
Thanks so much for the answer. I think I got it working in a hard way, but I will definetely try your solution, it looks a lot smarter than mine.
Thanks again,
Zhe Li
José-Luis
José-Luis 2013 年 1 月 10 日
My pleasure, please don't forget to accept an answer if it helps you.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by