A Guide to MATLAB for Beginners and Experienced Users

Chapter 7: MATLAB Programming

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!

Tip

Many MATLAB commands are themselves M-files, which you can examine using type or edit (for example, 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...

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: Robot Software
Finish!
Privacy Policy

This is embarrasing...

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