# While loop until value falls within a range

I’d like to be able to randomly pick a species that has a trophic level within a certain range.

``````num_animals = 40
trophic_position = rand(num_animals)

function target_species_check_change()
sp = rand((num_animal),1)
while (trophic_position[sp] < 0.3) && (trophic_position[sp] > 0.4)
sp = rand((num_animal),1)
end
return sp
end

target_species = target_species_check_change()

``````

I would just want the number of the species (1:40) to be returned which corresponds to a trophic level between 0.3 and 0.4

The syntax to pick a random integer within a range is

``````sp = rand(1:num_animals)
``````

Thank you for your reply, I have updated by code below. I am unable to generate a `target_species` that has a `trophic_position` between `0.3` and `0.4`.

``````num_animals2 = 40
trophic_position2 = rand(num_animals2)

function target_species_check_change2()
sp = rand((1:num_animals2),1)[1]
while (trophic_position2[sp] < 0.3) && (trophic_position2[sp] > 0.4)
sp = rand((1:num_animals2),1)[1]
end
return sp
end

target_species = target_species_check_change()
trophic_position[target_species]
``````

You have to use `||` instead of `&&`, or the `while` loop will never execute (since there is no number that is smaller than 0.3 and larger than 0.4).

Note that you can also replace `rand((1:num_animals2),1)[1]` by `rand(1:num_animals2)`. Right now you are allocating an unnecessary 1-element array every time.

Thank you for your reply. I though `||` means or from here.

I understand why `&&` would not work from your explanation. There is probably a less confusing way to write my function.

It does mean “or”, which is what you want here.

I believe the following code does what you want more cleanly. I replaced your `while` loop with elementwise broadcasting indicated by `.`.

``````num_animals=40
trophic_position=rand(num_animals) #Create trophic position data for each animal
trophic_position_within_range=(trophic_position.>0.3) .& (trophic_position.<0.4) #Vector of true/false
animals_within_range=(1:num_animals)[trophic_position_within_range] #Vector of animals where trophic_position_within_range is true
random_animal_in_range=rand(animals_within_range) #Selects a random animal from the previous vector
``````

or as a function:

``````function select_animal(num_animals,lower_bound,upper_bound)
trophic_position=rand(num_animals)
trophic_position_within_range=(trophic_position.>lower_bound) .& (trophic_position.<upper_bound)
animals_within_range=(1:num_animals)[trophic_position_within_range]
random_animal_in_range=rand(animals_within_range)
end

chosen_animal=select_animal(40,0.3,0.4)
``````