I have a variable 'n'. I want n to take a value 1 or 2 randomly. how do i code it?

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)

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);
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

So is N the number of times the loop runs? As in here the loop will run 6 time right?
Correct.
I set ‘N’ to be a variable to make the code easier to modify to do what you want.

This question is closed.

Asked:

on 29 Nov 2015

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!