How to locate the first negative number?

77 views (last 30 days)
%Amount of user numbers
n=input('Amount of user: ');
D=randn(n,1); %Random numbers
disp('Random numbers generated:');
disp(D);
i=1:1:n;
l=0;
while D(i,1)>0
l=l+1;
end
if l>n
l=('Não existe');
else
l=l+1;
end
disp('the first negative number is:');
disp(l);
Where is the error? Thanks!

Accepted Answer

Guillaume
Guillaume on 9 Nov 2014
Use find to locate something in an array:
l = find(D < 0, 1);
If you want to use a while loop, it should be:
%no need for index i, which you never increased anyway
l = 1; %can't index at 0
while l <= n && D(l) > 0 %order of comparison is important to prevent D(l) being evaluated when l >n
l = l+1;
end
  1 Comment
Guillaume
Guillaume on 9 Nov 2014
Also note that your original
while D(i) > 0
when i is 1:numel(D), will only be true when all elements of D are positive. In which case, your loop will run forever.

Sign in to comment.

More Answers (1)

Rômulo Prazeres
Rômulo Prazeres on 9 Nov 2014
Thank you so much. =D

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!