Chapter 6

Programming in MATLAB

A computer program is a sequence of computer commands. In a simple program the commands are executed one after the other in the order they are typed. In this book, for example, all the programs that have been presented so far in script files are simple programs. Many situations, however, require more sophisticated programs in which commands are not necessarily executed in the order they are typed, or different commands (or groups of commands) are executed when the program runs with different input variables. For example, a computer program that calculates the cost of mailing a package uses different mathematical expressions to calculate the cost depending on the weight and size of the package, the content (books are less expensive to mail), and the type of service (airmail, ground, etc.). In other situations there might be a need to repeat a sequence of commands several times within a program. For example, programs that solve equations numerically repeat a sequence of calculations until the error in the answer is smaller than some measure.

MATLAB provides several tools that can be used to control the flow of a program. Conditional statements (Section 6.2) and the switch structure (Sections 6.3) make it possible to skip commands or to execute specific groups of commands in different situations. For loops and while loops (Sections 6.4) make it possible to repeat a sequence of commands several times.

It is obvious that changing the flow of a program ...

Get MATLAB: An Introduction with Applications 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.