Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to using a while loop inside a for loop in Matlab. The while loop will repeat the same action until it satifies some criteria. The outcome from the while loop is one iteration in the for loop. I am having a problem to get that correctly.

n=100;
for i=1:n
    while b<0.5
        x(i)=rand;
        b=x(i);
    end
end

I am not sure what i am doing wrongly. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
136 views
Welcome To Ask or Share your Answers For Others

1 Answer

Approach the problem differently. There's no need to try again if rand doesn't give you the value you want. Just scale the result of rand to be in the range you want. This should do it:

x = 0.5 + 0.5*rand(1, 100);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...