My script won't run (error) how do I fix it?

14 ビュー (過去 30 日間)
Charlotte Davies
Charlotte Davies 2017 年 4 月 12 日
編集済み: Charlotte Davies 2017 年 4 月 12 日
My script is below. When it runs (using [left, right] = search(a, 367, 1, 100)) it shows this message: Index exceeds matrix dimensions.
Error in search (line 12) if vec(midPt) == targetVal
It should output the index 73 - how can I fix it?
My Script:
function [left, right] = search(vec,targetVal,left,right)
% SEARCH Binary search algorithm step.
% [left, right] = SEARCH(vec,targetVal,left,right) returns the end points
% produced by one step of the binary search algorithm with
% target value targetVal. The elements of vec must be in ascending order.
% Compute the mid-point by halving the distance between
% the end points and rounding to the nearest integer.
while left < right
midPt = round((left + right)/2)
if vec(midPt) == targetVal
% targetVal has been found
left = midPt;
right = midPt;
elseif vec(midPt) < targetVal
% targetVal must be before midPt
right = midPt - 1;
else
% targetVal must be after midPt
left = midPt + 1;
end
end

採用された回答

KSSV
KSSV 2017 年 4 月 12 日
For [left, right] = search(a, 367, 1, 100) ;
left = 1; right = 100 ; midPt = round((left + right)/2) ; midpt = 51
Your size of a would be less then 51, so the error popped out. Check your size of a
  1 件のコメント
Charlotte Davies
Charlotte Davies 2017 年 4 月 12 日
編集済み: Charlotte Davies 2017 年 4 月 12 日
Thank you! I entered in the vector a = primes(541) which fixed this issue, but then I only received midpoints 51, 26, 13, 7, 4 and 2 and both left and right equal to 1 which makes no sense as the index for the target value is 73 (which should be output as the final value of left and right, and the midpoints should approach 73 rather than 1). What should I do?

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

その他の回答 (1 件)

Roger Stafford
Roger Stafford 2017 年 4 月 12 日
編集済み: Roger Stafford 2017 年 4 月 12 日
The error message probably occurs when your vector ‘vec’ does not contain the value ‘targetVal’. In that case you repeatedly either reduce ‘right’ or else repeatedly increase ‘left’ until one of them goes below 1 or the other above 100, at which time you will be beyond the index limits in ‘vec’. You need to avoid getting right < left.

カテゴリ

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