So I have arr = randi([0,20],20,1). I want to show: If there are numbers less than 5, fprintf('Yes\n') only once. Im using a for loop (for i = 1 : length(arr)) and indexing it.
You can use a break
statement upon finding the first value under 5 and printing the Yes
statement.
break
Statement:arr = randi([0,20],20,1);
for i = 1: length(arr)
if arr(i) < 5
fprintf("Yes\n");
break;
end
end
any()
Function:Alternatively, if you'd like to concise it down without the need for a for-loop the any()
function can be used to determine if any values within the array meet a condition in this case arr < 5
.
arr = randi([0,20],20,1);
if(any(arr < 5))
fprintf("Yes\n");
end
Check = 0;
arr = randi([0,20],20,1);
i = 1;
while (Check == 0 && i < length(arr))
if arr(i) < 5
fprintf("Yes\n");
Check = 1;
end
i = i + 1;
end