Difference between randi(1,M) and randi() in for loop

13 views (last 30 days)
Are there any difference between A and B?
randi(1,M);
and
for k=1:M
randi(1,1);
end

Accepted Answer

Sebastian Castro
Sebastian Castro on 19 May 2016
Edited: Sebastian Castro on 19 May 2016
Results-wise, there is no difference. Both snippets of code below generate a 5-element vector of random numbers between 1 and 10.
To get equivalent results, I am forcing the random number generator seed to be 0 using rng.
% Single command
rng(0)
x = randi(10,1,5)
x =
9 10 2 10 7
vs.
% for-loop
rng(0)
x = zeros(1,5);
for k=1:5
x(k) = randi(10);
end
x
x =
9 10 2 10 7
Now, the recommended way is to use the single command because it's likely more optimized than the brute-force for-loop approach. This will become apparent especially if you're generating large matrices.
tl;dr use a single command. It's the same and the syntax is both easier and faster.
- Sebastian

More Answers (0)

Categories

Find more on Random Number Generation in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!