I have a variable 'n'. I want n to take a value 1 or 2 randomly. how do i code it?
Info
This question is closed. Reopen it to edit or answer.
Show older comments
I have a very basic question.
The thing is I want to run a loop and each time the loop runs, n should take the value either 1 or 2 randomly.
Answers (2)
Geoff Hayes
on 29 Nov 2015
Aanandita - use randi to generate a random integer between 1 and a maximum integer of your choice. If you want the random integer to be one or two, then just do
n = randi(2);
Star Strider
on 29 Nov 2015
This works:
N = 6;
for k1 = 1:N
n(k1) = randi(2);
end
although you can do the same thing much more efficiently in one line without the loop:
n = randi(2, 1, N);
2 Comments
Aanandita Katre
on 29 Nov 2015
Star Strider
on 29 Nov 2015
Correct.
I set ‘N’ to be a variable to make the code easier to modify to do what you want.
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!