Filter löschen
Filter löschen

Issue with random function

8 Ansichten (letzte 30 Tage)
Matt
Matt am 21 Sep. 2015
Bearbeitet: Stephen23 am 21 Sep. 2015
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.

Akzeptierte Antwort

Matt
Matt am 21 Sep. 2015
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 Kommentare
Matt
Matt am 21 Sep. 2015
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 am 21 Sep. 2015
Bearbeitet: Stephen23 am 21 Sep. 2015
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));

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

James Tursa
James Tursa am 21 Sep. 2015
What is the class of the variable random? Is it a double at the command line but something else in your script?
  2 Kommentare
Matt
Matt am 21 Sep. 2015
I have declared it as being zeros right before the for loop:
random=zeros(25, 3)
Matt
Matt am 21 Sep. 2015
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by