I want to write a function which takes as input three integers a, b and c, and generates and returns a random integer that is equally likely to take any value between a and b (inclusive), but will not return the value given by c.
Show older comments
This is what I have so far:
function f = randnum_reject(a,b,c)
randnum_reject = (b-a)*rand + a;
f = randnum_reject;
if f == c
f = (b-a)*rand + a;
else
f = randnum_reject;
end
end
I know I probably made the mistake right after I assigned the output to f. I just really don't have any ideas as to how exclude c when I call random numbers from a to b
2 Comments
Walter Roberson
on 14 Nov 2013
Is c always a single value or could it be a vector of values to avoid?
Alex Benavides
on 14 Nov 2013
Answers (2)
Roger Stafford
on 14 Nov 2013
You don't need a for-loop for this problem.
p = [a:c-1,c+1:b];
f = p(ceil((b-a)*rand));
6 Comments
Image Analyst
on 14 Nov 2013
Edited: Image Analyst
on 14 Nov 2013
You can also use randi() to pick out one of the possible values:
f2 = int32(p(randi(length(p))))
I also added int32() to make the type of variable a true integer instead of a double that just happened to have an integer for a value.
Alex Benavides
on 14 Nov 2013
Walter Roberson
on 14 Nov 2013
Yes, It is possible to program it without an "if" statement.
Alex Benavides
on 14 Nov 2013
Edited: Alex Benavides
on 14 Nov 2013
Walter Roberson
on 14 Nov 2013
What error does it give, with what inputs ?
Walter Roberson
on 14 Nov 2013
p( randperm(length(p),1) )
if your MATLAB is a newer one.
Walter Roberson
on 14 Nov 2013
0 votes
Do not use a variable with the same name as your function. Inside your function rename the variable randum_reject to something else.
6 Comments
Walter Roberson
on 14 Nov 2013
Infinite loop. Try something. Was the result acceptable? If it was, return it. Otherwise loop again.
Alex Benavides
on 14 Nov 2013
Walter Roberson
on 14 Nov 2013
What was your trial code along these lines?
Alex Benavides
on 14 Nov 2013
Image Analyst
on 15 Nov 2013
Are you not wanting to try any of the working solutions under Roger's answer for some reason, and are continuing to use your code (which you admit doesn't work)? If so, why?
Walter Roberson
on 15 Nov 2013
What code was it that you tested that did not skip the value it was supposed to?
Categories
Find more on Random Number Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!