If statement correction help

3 ビュー (過去 30 日間)
Tony Chan
Tony Chan 2019 年 3 月 11 日
編集済み: per isakson 2019 年 3 月 11 日
Hi I am trying to write an if statement. What I need is to create an array of 1000 random variables from -1 to 0 and 1/2 to 1. My algorithm is if the number in that element is less than 0 and greater than 0.5, move onto the next, if not repeat but doesn't not seem to work when I check the resulting array. Sorry if this may be rudimentary but so far I wrote:
X1 = zeros(1, 1e3);
for i=1:numel(X1);
X1(i)=-1+(2)*rand(1);
if X1(i) < 0 & X1(i) > 0.5;
i=i+1;
else
i=i;
end
end
Thank you so much, I appreciate the help.
  2 件のコメント
madhan ravi
madhan ravi 2019 年 3 月 11 日
編集済み: madhan ravi 2019 年 3 月 11 日
flip the direction of relational operators and use && instead of &
Walter Roberson
Walter Roberson 2019 年 3 月 11 日
It is not possible for a number to be sumultaneously less than 0 and greater than 1/2 . You might want to use | instead of & or you might want to use > and < instead of < and >
Note that any change you make to a loop control variable such as i inside the loop will be ignored on the next iteration of the loop. You cannot cause a particular for iteration to repeat by adjusting the loop control variable. Consider using while

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

回答 (1 件)

per isakson
per isakson 2019 年 3 月 11 日
編集済み: per isakson 2019 年 3 月 11 日
"I need is to create an array of 1000 random variables from -1 to 0 and 1/2 to 1"
Another approach
>> X1 = rand(1,1e3)*1.5 - 1;
>> X1(X1>0) = X1(X1>0)+0.5;
>> plot(X1,'.')
or to get the "same" number of elements in each interval
>> X1 = rand(1,1e3)*2 - 1;
>> X1(X1>0) = X1(X1>0)/2 + 0.5;
>> plot(X1,'.')

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by