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
댓글 수: 0
답변 (1개)
Walter Roberson
2017년 9월 11일
You should use either a while loop or a for loop, but not both.
댓글 수: 2
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!