-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

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Linda Rabady
  • 225
  • 2
  • 4
  • 8
  • 2
    what is wrong with the code? what exactly is the problem? – Shai Sep 10 '13 at 21:56
  • 2
    BTW, it is best [not to use `i` as a variable name in Matlab](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab) – Shai Sep 10 '13 at 21:57
  • 3
    you probably have to initialize `b` before first calling the `while`-statement – Schorsch Sep 10 '13 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. – Linda Rabady Sep 10 '13 at 22:01

2 Answers2

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);
Peter
  • 14,559
  • 35
  • 55
  • I like your approach however Schorsch's approach is more relevant to my problem. – Linda Rabady Sep 10 '13 at 22:12
  • @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. – Eitan T Sep 11 '13 at 06:54
  • @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 Sep 12 '13 at 15:29
  • @Schorsch Hence my plead for more details :) – Eitan T Sep 12 '13 at 16:29
  • 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. – Linda Rabady Sep 14 '13 at 01:03
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
Schorsch
  • 7,761
  • 6
  • 39
  • 65