Repeat for loop until condition is met.

4 visualizaciones (últimos 30 días)
Matlab User
Matlab User el 2 de Mzo. de 2017
Comentada: John BG el 2 de Mzo. de 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 comentario
John BG
John BG el 2 de Mzo. de 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

Iniciar sesión para comentar.

Respuesta aceptada

James Tursa
James Tursa el 2 de Mzo. de 2017
Editada: James Tursa el 2 de Mzo. de 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

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by