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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by