## Loop Constructs

Though MATLAB has a number of built-in functions that are equivalent to some of
the following exercises, use a loop construct to carry out the indicated computations.
It will probably be easiest to write a short script since these are inherently
multi-line problems.

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

1. Given the vector x = [1 8 3 9 0 1], create a short set of commands that will
a. Add up the values of the elements (Check with **sum**.)
b. Computes the running sum (for element j, the running sum is the sum of the
elements from 1 to j, inclusive. Check with **cumsum**.)
c. computes the sine of the given x-values (should be a vector)
ans.
2. Create an M-by-N array of random numbers (use **rand**). Move through the
array, element by element, and set any value that is less than 0.2 to 0 and any
value that is greater than (or equal to) 0.2 to 1.
ans.
3. Given x = [4 1 6] and y = [6 2 7], compute the following arrays
a. a_{ij} = x_{i}y_{j}
b. b_{ij} = x_{i}/y_{j}
c. c_{i} = x_{i}y_{i}, then add up the elements of c.
d. d_{ij} = x_{i}/(2 + x_{i} + y_{j})
e. e_{ij} = reciprocal of the lesser of x_{i} and y_{j}
ans.
4. Write a script that will use the random-number generator **rand** to determine the
following:
a. The number of random numbers it takes to add up to 20 (or more).
b. The number of random numbers it takes before a number between 0.8 and
0.85 occurs.
c. The number of random numbers it takes before the mean of those numbers
is within 0.01 of 0.5 (the mean of this random-number generator).
It will be worthwhile to run your script several times because you are dealing
with random numbers. Can you predict any of the results that are described above?
ans.
5. Write a script that asks for a temperature (in degrees Fahrenheit) and computes
the equivalent temperature in degrees Celcius. The script should keep running
until no number is provided to convert. [NB. the function `isempty` will be useful
here.]
ans.

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

Comments? Contact Jim Maneval at
`maneval@bucknell.edu`