While loop inside for loop in Matlab

我只是一个虾纸丫 提交于 2019-12-13 08:57:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!