Repeat for loop until condition is met.

4 次查看(过去 30 天)
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 个评论
John BG
John BG 2017-3-2
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

请先登录,再进行评论。

采纳的回答

James Tursa
James Tursa 2017-3-2
编辑:James Tursa 2017-3-2
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by