Book contents
- Frontmatter
- Contents
- Preface
- 1 Getting Started
- 2 MATLAB Basics
- 3 Interacting with MATLAB
- Practice Set A: Algebra and Arithmetic
- Practice Set B: Calculus, Graphics, and Linear Algebra
- 6 MATLAB Programming
- 7 Publishing and M-Books
- 8 Simulink
- 9 ☆ GUIs
- 10 Applications
- Practice Set C: Developing Your MATLAB Skills
- Solutions to the Practice Sets
- Glossary
- Index
6 - MATLAB Programming
Published online by Cambridge University Press: 05 September 2012
- Frontmatter
- Contents
- Preface
- 1 Getting Started
- 2 MATLAB Basics
- 3 Interacting with MATLAB
- Practice Set A: Algebra and Arithmetic
- Practice Set B: Calculus, Graphics, and Linear Algebra
- 6 MATLAB Programming
- 7 Publishing and M-Books
- 8 Simulink
- 9 ☆ GUIs
- 10 Applications
- Practice Set C: Developing Your MATLAB Skills
- Solutions to the Practice Sets
- Glossary
- Index
Summary
Every time you create an M-file, you are writing a computer program using the MATLAB programming language. You can do quite a lot in MATLAB using no more than the most basic programming techniques that we have already introduced. In particular, we discussed simple loops (using for) and a rudimentary approach to debugging in Chapter 3. In this chapter, we will cover some further programming commands and techniques that are useful for attacking more complicated problems with MATLAB. If you are already familiar with another programming language, much of this material will be quite easy for you to pick up!
✓ Many MATLAB commands are themselves M-files, which you can examine using type or edit, e.g., enter type isprime to see the M-file for the command isprime. You can learn a lot about MATLAB programming techniques by inspecting the built-in M-files.
Branching
For many user-defined functions, you can use a function M-file that executes the same sequence of commands for each input. However, one often wants a function to perform a different sequence of commands in different cases, depending on the input. You can accomplish this with a branching command, and, as in many other programming languages, branching in MATLAB is usually done with the command if, which we will discuss now. Later we will describe the other main branching command, switch.
Branching with if
For a simple illustration of branching with if, consider the following function M-file absval.m, which computes the absolute value of a real number.
- Type
- Chapter
- Information
- A Guide to MATLABFor Beginners and Experienced Users, pp. 85 - 102Publisher: Cambridge University PressPrint publication year: 2006