How do I find a value in a vector using the bisection method?

1 回表示 (過去 30 日間)
Brady Retzlaff
Brady Retzlaff 2015 年 10 月 12 日
コメント済み: Walter Roberson 2015 年 10 月 12 日
I'm asked to find the location of the value 25 in a 200 value vector that is in ascending order using the bisection method. So far I have this:
xl=1;
xr=200;
xc=100;
for(j=1:100)
xc=(xl+xr)/2;
floor(xc);
fc=(25-xc);
if(fc<0)
xr=xc;
else
xl=xc;
end
if abs(fc)==0
break
end
end
fc
xc
j
And it spits out 0, 25, and 55 for fc, xc, and j respectively.
I'm pretty sure my code is wrong, so I need help on that, but also once I get it right how do I describe the location?

回答 (2 件)

Walter Roberson
Walter Roberson 2015 年 10 月 12 日
Your code is not finding the location that contains 25, your code is looking for index 25. Your checking should not be against xc, your checking should be against the vector indexed at floor(fc)
  2 件のコメント
Brady Retzlaff
Brady Retzlaff 2015 年 10 月 12 日
so how do i specify in the code that i am looking for the location that contains 25?
Walter Roberson
Walter Roberson 2015 年 10 月 12 日
xcidx = floor(xc);
fc = 25 - YourVectorOf200Elements(xcidx);

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


Eng. Fredius Magige
Eng. Fredius Magige 2015 年 10 月 12 日
編集済み: Walter Roberson 2015 年 10 月 12 日
Hi
the uses of
xl=1;
xr=200;
xc=100;
not observed in for(j=1:100) applicability as varies 1:1:100; and intentional use; I though sometning left, might be xr or xc as to varies as j added or substracted. Note from you explanation could be new=xr+(xr+xc)/2
thanks
  2 件のコメント
Brady Retzlaff
Brady Retzlaff 2015 年 10 月 12 日
i dont understand this at all...
Walter Roberson
Walter Roberson 2015 年 10 月 12 日
I do not understand it either.

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by