Essential MATLAB for Engineers and Scientists, Third Edition

Chapter 8: Loops

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.

8.1 Determinate Repetition with for

8.1.1 Binomial Coefficient

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.

UNLIMITED FREE
ACCESS
TO THE WORLD'S BEST IDEAS

SUBMIT
Already a GlobalSpec user? Log in.

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.

Customize Your GlobalSpec Experience

Category: Loop Powered Devices
Finish!
Privacy Policy

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.