フィルターのクリア

Issue with random function

8 ビュー (過去 30 日間)
Matt
Matt 2015 年 9 月 21 日
編集済み: Stephen23 2015 年 9 月 21 日
Hello guys,
I have an issue with the function RANDOM that is not producing random numbers as it should. Here is the code:
for j=1:25
random(j, 1)=rand*(time(j, 1)/2);
random(j, 2)=rand*(time(j, 1)/2);
random(j, 3)=rand*(time(j, 1)/2);
end
If I input this in the command window and assign a value to "time", it works, but in my script, I am always getting the same number on every column! I tried to debug it with breakpoints, but I cannot see why from one line to the other, the "rand" function cannot produce random numbers.
Also inside this for loop, I then have different assignments to the time matrix, eg: time(j, 2) or time(j, 3) so it is not ok to just generate random numbers. I have to connect them with specific entries of the time matrix.

採用された回答

Matt
Matt 2015 年 9 月 21 日
I found the issue to the problem. I named a variable "rand" earlier in my code. Matlab didn't give me any information this would in fact replace the function RAND by the value of the variable rand I declared, so effectively the RAND function was not producing random numbers anymore!
I didn't know using a variable called rand would overwrite Matlab's RAND function. Good to know, problem solved! :-)
  3 件のコメント
Matt
Matt 2015 年 9 月 21 日
Yes. I remember reading something similar to "this is a variable allowed to matlab, it may cause issues to use it", but I cannot remember in what condition.
I just assumed it would not overwrite the function, as I implicitly never used variable names such as sum or mean.
Stephen23
Stephen23 2015 年 9 月 21 日
編集済み: Stephen23 2015 年 9 月 21 日
Rather than doing this in a loop, it would be faster and more efficient to generate the random numbers all at once. This avoids having to expand the output array in a loop, which is very inefficient.
>> X(:,1) = 0:24;
>> Y = bsxfun(@times,X/2,rand(25,3));

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

その他の回答 (1 件)

James Tursa
James Tursa 2015 年 9 月 21 日
What is the class of the variable random? Is it a double at the command line but something else in your script?
  2 件のコメント
Matt
Matt 2015 年 9 月 21 日
I have declared it as being zeros right before the for loop:
random=zeros(25, 3)
Matt
Matt 2015 年 9 月 21 日
I must add that when I put the command RAND right after the start of the for loop, and then just RAND again before the end of the loop, I get the same number! Why is not not generating random numbers all the time? Strange.

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

カテゴリ

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