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

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

댓글을 달려면 로그인하십시오.

 채택된 답변

Sebastian Castro
Sebastian Castro 2016년 5월 19일
편집: Sebastian Castro 2016년 5월 19일
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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 C2000 Microcontroller Blockset에 대해 자세히 알아보기

태그

질문:

2016년 5월 19일

댓글:

2016년 5월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by