Repeat for loop until condition is met.

4 vues (au cours des 30 derniers jours)
Matlab User
Matlab User le 2 Mar 2017
Commenté : John BG le 2 Mar 2017
I am drawing random numbers within an interval. I know that in the end I want 20 of them, but only those that meet a condition, for example, generation between 1:10 and then only keeping those less than 5. I need to loop over this until 20 are found... I'm not allowed to just generate between 1:5 which would solve this unfortunately! I have something like this..
Number_req=20;
n = zeros(20,1);
for k=1:Number_req
x=[];
x=10*rand(1,1);
if x(k)<= 10
n(k) = x
else
if x(k)>10
break
end
end
end
  1 commentaire
John BG
John BG le 2 Mar 2017
who or what is not allowing you to just do the following
randi([1 4],1,20)
generating random numbers within [1:10] but not getting any within [5:10] is, if not considering time, exactly the same as generating random numbers within [1:4]
are you familiar with the Bayes theorem?
John BG

Connectez-vous pour commenter.

Réponse acceptée

James Tursa
James Tursa le 2 Mar 2017
Modifié(e) : James Tursa le 2 Mar 2017
It would be easier to use a while loop. E.g., modifying your code and replacing your for-loop with a while-loop:
% Insert your beginning stuff here
k = 1;
while k <= Number_req
r = _______; % insert your random number generation stuff here
if( ____________ ) % Insert your test code for r here
x(k) = r;
k = k + 1;
end
end
  1 commentaire
Matlab User
Matlab User le 2 Mar 2017
Thank you very much!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by