M BUZZ CRAZE NEWS
// news

If, else-if loops in matlab

By David Jones
$\begingroup$

I'm having a bit of confusion with matlab. I'm trying to generate a random number between zero and one, and then map that number to the set $\{0,1,2,3,4\}$. Here's the code I have:

x=rand(1)
if( x < 3.2e-4) k = 0
elseif( 3.2001e-4 < x < 6.72e-3) k = 1
elseif(6.72001e-3 < x < 0.05792) k = 2
elseif(0.05792001 < x < 0.2627) k = 3
elseif(0.2627001 < x < 0.6723) k=4
else k = 5
end

Whenever I run the code, it only works part of the time. For example, when I got x=0.5469, it says that k=5 when in reality k should take on the value of 4.

Any help/links are appreciated. Thanks in advance.

$\endgroup$ 2

3 Answers

$\begingroup$

The "if a < x < b" does not do what you think it does. Use "if a < x && x < b" instead. Extra credit: figure out how a < x < b actually evaluates.

$\endgroup$ $\begingroup$

To determine if a value falls within a range, you can use two separate comparison tests, joined with an AND condition, e.g.,

elseif ((3.2001e-4 < x) && (x < 6.72e-3))

There is another issue with the code above. if x is 3.20009e-4, you get k = 5, which is not what you want. What you should test for is:

elseif ((3.2e-4 <= x) && (x < 6.72e-3))

However, you can simplify the code above further. If the first test (x < 3.2e-4) is false, then (3.2e-4 <= x) is true, and the execution would go to the next else statement anyway, so you can just check for:

elseif (x < 6.72e-3)
$\endgroup$ $\begingroup$

You can also simplify this as:

if( x < 3.2e-4) k = 0
elseif (x < 6.72e-3) k = 1
elseif (x < 0.05792) k = 2
elseif (x < 0.2627) k = 3
elseif (x < 0.6723) k = 4
else k = 5
end
$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy