Is there any alternative way for multiple if else statement ?

5 views (last 30 days)
Hi all, I have to generate a random number between some ranges. say for ex. the ranges are [187 192 194 197 207] holding variable names q1,q2,q3,q4,q5 respectively. if the input value is 200, the answer should be any random number between q4 to q5 and similarly if the input value is 194, the answer should be between q2 to q3.
I have used multiple if statements to accomplish this. Is there any other simpler method in matlab?? Thanks for your help in advance.

Answers (2)

Guillaume
Guillaume on 18 Dec 2017
Firstly,
"variable names q1,q2,q3,q4,q5"
As soon as you start creating numbered variables (or any sequentially named variables) you need to say to yourself: I'm doing this wrong. These variables are obviously related so they belong together in a container that can be indexed, matrix, cell array, whatever. See for example Pierre's answer that group them together in a vector.
Multiple if statements are indeed rarely the most efficient way of doing anything. In your case, there are many faster way to achieve your result. In newer versions of matlab (>= R2015a) this would be
range = [187 192 194 197 207]; %demo data, must be monotonically increasing
%Q = [q1 q2 q3 q4 q5]; %the individual qi should never exist
Q = [0 0.8 1.5 2.3 7.9 10.2]; %demo data
v = randi([187, 207], 1, 10); %demo data
whichrange = discretize(v, range);
out = rand * (Q(whichrange+1) - Q(whichrange)) + Q(whichrange)
Another way to obtain the same result, which should work in any version of matlab but only for scalar v:
whichrange = find(v >= range & v <= range(end), 1, 'last');
out = rand * (Q(whichrange+1) - Q(whichrange)) + Q(whichrange)

Pierre Lecuyer
Pierre Lecuyer on 8 Dec 2017
Say you have
Q = [q1 q2 q3 q4 q5]
To determine which of these 4 ranges your randomly generated value v falls in, assuming q1 < v < q5 and Q is sorted, do the following :
find(histcounts(v,Q)))
Example :
>> Q = [5 12 23 45 50];
>> find(histcounts(20,Q))
ans =
2
  4 Comments
Adam
Adam on 18 Dec 2017
histcounts was introduced in R2014b so if you are using an earlier version it will not be available. If you are using R2014b or later then it should be.
Guillaume
Guillaume on 18 Dec 2017
Undefined function 'histcounts'
Most likely, you're running an old version of Matlab, before R2014b when the function was introduced.
It's always a good idea to mention in your question when you're using older versions.
Note that in even newer versions of matlab (R2015a or later), find(histcount(v, Q)) is simply discretize(v, Q) which has the added advantage of working with non-scalar v.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!