Repeat for loop until condition is met.

4 visualizzazioni (ultimi 30 giorni)
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 Commento
John BG
John BG il 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

Accedi per commentare.

Risposta accettata

James Tursa
James Tursa il 2 Mar 2017
Modificato: James Tursa il 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

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by