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 件のコメント

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 5 月 19 日
Your question is not clear. Your for loop doesn't do anything

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

 採用された回答

Sebastian Castro
Sebastian Castro 2016 年 5 月 19 日
編集済み: Sebastian Castro 2016 年 5 月 19 日

0 投票

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

1 件のコメント

Nancy Chen
Nancy Chen 2016 年 5 月 19 日
Thank you so much! The answer is clear. :)

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

その他の回答 (0 件)

カテゴリ

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by