While loop to find index of first element to be less than and greater than in a vector
84 views (last 30 days)
I have the following problem:
"Using a while loop, find the first element and its index in the variable "a" that is greater than 0.42 and less than 0.52. Make sure that your code does not evaluate indices greater than 20"
I wrote the following code:
while a(n) < 0.42 && a(n) > 0.52
However, absolutely nothing happens (no output is dispalyed) and I don't understand why. Can somebody please explain to me what I'm doing wrong?
I also don't know how to write the code so that it doesn't evaluate indices greater than 20. Can I use an if statement inside the while loop? Although I'm not sure how to do that exactly. Does anybody have any hints maybe?
Awais Saeed on 16 Nov 2021
Is it necessary to use a while loop? For loop works fine
a = rand(20,1)
for itr = 1:1:length(a) % iterate thorugh a row vector
if (a(itr) > 0.42 && a(itr) < 0.52) % id condition meets
index = itr % get the index
element = a(itr) % get element
Jan on 16 Nov 2021
Edited: Jan on 16 Nov 2021
It is impossible, that a number is smaller than 0.42 and greater than 0.52:
a(n) < 0.42 && a(n) > 0.52
% ^ ^ swap the operators...
Therefore this loop is not entered in any case.
The test for limiting n to 20 is missing. If any index is found, the loop can stop also. Both conditions match into the WHILE condition also:
while isempty(index) && n <= 20 && ... insert the fixed comparison
For completeness: An experienced Matlab programmer would write:
Index = find(0.42 < a & a < 0.52, 1);
Sometimes it is strange if a homework question forces you to use Matlab in a most unmatlabish way.
Image Analyst on 16 Nov 2021
You need to use OR (||) not AND (&&):
index = 1;
outOfRange = a(index) < 0.42 || a(index) > 0.52
while outOfRange && index < 20
outOfRange = a(index) < 0.42 || a(index) > 0.52;
fprintf('Found %f at index %d.\n', a(index), index)