how to check if random number is equal to 1

Hello World,
I wanted my code to work if a random drawn number is equal to 1 then another variable 'r' = 1
code is below, but doesnt seem to work
Please can somebody help me,
thanks Steven
x = [1,3,3]
total = total + x(randi(length(x)))
if x(randi(length(x))) == 1
r = 1;
end

6 Comments

Please elaborate on the phrase "doesn't work". Describe the result you were expecting and how that doesn't match the result you are getting.
Sometimes if my random drawn number is a 3, then r will still equal 1, sometimes when my random number is a 1 r doesnt equal 1. thanks Steven.
How do you know the value of the random number used in the if condition expression?
You call randi twice, there is no reason to expect that both calls will produce the same value. Atfer all, that is rather the point of random number generators.
hi i assumed the randon number called in 'total' and the random number called in the if statement are the same? If this isnt the case then is there a way to check if the random number in the total = 1 and if it does, then let r = 1. Your help would be very much appreicated. thanks Steven
"hi i assumed the randon number called in 'total' and the random number called in the if statement are the same?"
That is a highly unusual expectation from a random number generator, that it should repeatedly return the same value.
i am quite new to matlab, is thete any way to check that if the random number in the total is a 1, then r should = 1, please, thanks.

Sign in to comment.

Answers (1)

x = [1,3,3];
v = randi(numel(x));
total = total + x(v);
if x(v) == 1
r = 1;
end

3 Comments

Also, Steven, if you are running this in the base workspace (as a script) rather than a function workspace, you may want to add an:
else
r = 0;
Or else "r" may persist its value from previous runs of the code.
Reminder: your v is going to have as many elements as x does, so your v is a vector. x(v) is going to be a vector. x(v) == 1 is going to be a vector. if applied to a vector is only true if all of the values in the vector are non-zero (true). Therefore the current code if x(v) == 1 is testing whether all of the x(v) entries happen to be 1 (which in this particular case would only happen if v is [1 1 1], which would happen roughly one time in 27). If that is your intention then it is recommended that you code if all(x(v) == 1) to emphasize to the reader that you really do want that particular test.

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Asked:

on 4 Mar 2020

Commented:

on 4 Mar 2020

Community Treasure Hunt

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

Start Hunting!