Repeat for loop until condition is met.

조회 수: 4 (최근 30일)
Matlab User
Matlab User 2017년 3월 2일
댓글: John BG 2017년 3월 2일
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