## Control of Flow: if-blocks

The following exercises are meant to be answered by a single MATLAB command. The command may be involved (i.e., it may use a number of parentheses or calls to functions) but can, in essence, be solved by the execution of a single command. If the command is too complicated, feel free to break it up over two or more lines.

[Back to main page] [Back to exercises page]

In each of the following questions, evaluate the given MATLAB code fragments for each of the cases indicated. Use MATLAB to check your answers.

```1.   if n > 1            a. n = 7   m = ?
m = n+1          b. n = 0   m = ?
else                c. n = -10 m = ?
m = n - 1
end
ans.

2.   if z < 5            a. z = 1    w = ?
w = 2*z          b. z = 9    w = ?
elseif z < 10       c. z = 60   w = ?
w = 9 - z        d. z = 200  w = ?
elseif z < 100
w = sqrt(z)
else
w = z
end
ans.

3.   if T < 30           a. T = 50    h = ?
h = 2*T + 1      b. T = 15    h = ?
elseif T < 10       c. T = 0     h = ?
h = T - 2
else
h = 0
end
ans.

4.   if 0 < x < 10           a. x = -1   y = ?
y = 4*x              b. x = 5    y = ?
elseif 10 < x < 40      c. x = 30   y = ?
y = 10*x             d. x = 100  y = ?
else
y = 500
end
ans.

```

Write brief scripts to evaluate the following functions. If you start each script with a request for input (using input), you'll be able to test that your code provides the correct results.

```5. h(T) = T - 10        when 0 < T < 100
= 0.45 T + 900  when T > 100

Test cases:  a. T = 5, h = -5
b. T = 110, h = 949.5

6. f(x) = -1     if x < 0
= 0      if x = 0
= 1      if x > 0

Compare your results to the MATLAB function sign.

7.  t(y) = 200                        when y is below 10,000
= 200 + 0.1 (y - 10,000)     when y is between 10,000 and 20,000
= 1,200 + 0.15 (y - 20,000)  when y is between 20,000 and 50,000
= 5,700 + 0.25 (y - 50,000)  when y is above 50,000

Test cases:  a. y = 5,000   t = 200
b. y = 17,000  t = 900
b. y = 25,000  t = 1,950
c. y = 75,000  t = 11,950

8. Explain why the following if-block would not be a correct solution to the
previous exercise.

if y < 10000
t = 200
elseif 10000 < y < 20000
t = 200 + 0.1*(y - 10000)
elseif 20000 < y < 50000
t = 1200 + 0.15*(y - 20000)
elseif y > 50000
t = 5700 + 0.25*(y - 50000)
end
ans.
```

[Back to main page] [Back to exercises page]
Comments? Contact Jim Maneval at maneval@bucknell.edu