Whenever I run this function, all is good if A(i)==N. However when it is not found, the function seems to run super slowly that i never end up getting the output of 0. Do I need to preallocate somewhere? If so, what would it be?

1 回表示 (過去 30 日間)
"Write a function, Finder, that receives an array of numbers A and a number N and returns the position of N within the array A or the value zero if N is not present within A."
function pos=Finder(A,N)
found=false;
while ~found
for i=1:length(A);
if A(i)==N;
found=true;
break
end
end
end
if found
pos=i;
else
pos=0;
end
end

回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 9 月 11 日
You should use either a while loop or a for loop, but not both.
  2 件のコメント
José-Luis
José-Luis 2017 年 9 月 11 日
On top of what Walter said, in your code, if it never gets found, your condition never gets set to true and you never break out of the while loop.
John D'Errico
John D'Errico 2017 年 9 月 11 日
The real question is, why not just use ismember?

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

カテゴリ

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