问题
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
回答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
回答2:
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);
来源:https://stackoverflow.com/questions/18729376/while-loop-inside-for-loop-in-matlab