MATLAB: How to locate the first negative number

first negative number

%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!

Best Answer

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