Essential MATLAB for Engineers and Scientists, Third Edition

The objectives of this chapter are to enable you to learn to:
Program (or code) determinate loops with for.
Program (or code) indeterminate loops with while.
In Chapter 2 we introduced the powerful for statement, which is used to repeat a block of statements a fixed number of times. This type of structure, where the number of repetitions must be determined in advance, is sometimes called determinate repetition. However, it often happens that the condition to end a loop is only satisfied during the execution of the loop itself. Such a structure is called indeterminate. This chapter is mainly about indeterminate loops, but to emphasize the difference between the two types of repetition we will first look at some more examples of for loops.
The binomial coefficient is widely used in mathematics and statistics. It is defined as the number of ways of choosing r objects out of n without regard to order, and is given by
If this form is used, the factorials can get very big, causing an overflow. But a little thought reveals we can simplify Equation (8.1) as follows:
Using Equation (8.2) is computationally much more efficient:
ncr = 1;n = ...r = ...for k = 1:r ncr = ncr * (n - k + 1) / k;enddisp( ncr )
The binomial coefficient is sometimes pronounced n-see-r . Work through the program by hand with some sample values.