How to locate the first negative number?
77 views (last 30 days)
Show older comments
Rômulo Prazeres
on 9 Nov 2014
Answered: Rômulo Prazeres
on 9 Nov 2014
%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!
0 Comments
Accepted Answer
Guillaume
on 9 Nov 2014
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
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.
More Answers (1)
See Also
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!