-1

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

4
  • 2
    what is wrong with the code? what exactly is the problem? Commented Sep 10, 2013 at 21:56
  • 2
    BTW, it is best not to use i as a variable name in Matlab Commented Sep 10, 2013 at 21:57
  • 3
    you probably have to initialize b before first calling the while-statement Commented Sep 10, 2013 at 21:58
  • I tried to initialise b but that doesnt work. I am trying to get a vector of x values with size(1x100) all values more than 0.5. the x value is randomly generated. Commented Sep 10, 2013 at 22:01

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

5 Comments

I like your approach however Schorsch's approach is more relevant to my problem.
@LindaRabady Why is it more relevant? Please add more details so that it can be answered properly then. If you're re-generating a random number using a loop to force it to be within a specific range, something in your initial approach is probably wrong.
@EitanT maybe the rand was just an example and the question really was about how to set up the statement so that it can be evaluated the very first time the while-statement is called. But that's just guesswork.
@Schorsch Hence my plead for more details :)
Thanks all, sorry for being late in my reply. yes the rand was just an example but the idea is excellent. I can use it somewhere else.
1

With the example you showed, you have to initialize b or the while-statement cannot be evaluated when it is first called.
Do it inside the for-loop to avoid false positives after the first for-iteration:

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

Or, without b:

n=100;
x = zeros(1,100);
for ii=1:n
    while x(ii)<0.5
        x(ii)=rand;
    end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.