Go back to initializing values using for loop when condition is not met

5 ビュー (過去 30 日間)
Mounisha Ganesan
Mounisha Ganesan 2019 年 7 月 10 日
コメント済み: infinity 2019 年 7 月 10 日
I have a for loop where I initiialize random values to variables and I check for certain condition, if my condition is not met I have to reinitialize the values for the same iteration. How do I do so?
Here's a sample
n = 100;
for i = 1:n
x(i) = rand
y(i) = rand
if(x(i)< 0 || y(i)<0)
disp(' I need to reinitialize values for the same i and my n count should be 100')
end
end
So I have to run the loop until I reach my 'n' value and meet my conditions within the loop. Is there a way to do it or should I use different loop like while?

採用された回答

infinity
infinity 2019 年 7 月 10 日
編集済み: infinity 2019 年 7 月 10 日
Hello,
There are several ways, one approach that you can use as follows
clear
n = 100;
x = zeros(1,n);
y = zeros(1,n);
for i = 1:n
xt = rand;
yt = rand;
while (xt*yt<0)
xt = rand;
yt = rand;
end
x(i) = xt;
y(i) = yt;
end
  6 件のコメント
Mounisha Ganesan
Mounisha Ganesan 2019 年 7 月 10 日
YES ! I did this already. That was my original code. But since x2 is( X2 = x1+ some value ) it might exceed value 1 or become less than 0. So I have to check for the x2 and y2 everytime so that they are between 0-1 and initialize x1 and y1 again for the same iteration until I make sure x2 and y2 are within (0-1)
infinity
infinity 2019 年 7 月 10 日
Hello,
I got your point. You can see my comment above, which is just modified.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by