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

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

1 commentaire

Your question is not clear. Your for loop doesn't do anything

Connectez-vous pour commenter.

 Réponse acceptée

Sebastian Castro
Sebastian Castro le 19 Mai 2016
Modifié(e) : Sebastian Castro le 19 Mai 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

Plus de réponses (0)

Catégories

En savoir plus sur Random Number Generation dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by