next up previous contents
Next: 1.6 Controlling output Up: 1. Getting started with Previous: 1.4.1 Arrays: vectors and   Contents

1.5 Avoiding carpal-tunnel syndrome: Using M-files

Before we go any farther, let's introduce a better way of interacting with MATLAB. You will quickly grow tired of entering a series of commands over and over in the exercises while you are experimenting. The easiest way to interact with MATLAB as you experiment with different commands is to use M-files. An M-file is nothing more than a text file with a list of commands that you want MATLAB to execute. In the words of the computer science people, it's a script. Put the commands in the file, then type the name of the file. That's it. Let's try an example. Go to the File menu, select new, and click on M-file. In the M-file, type the following
% This is our first script
% Lines with the '%' symbol are just comments
% Matlab ignores them
a = 1
b = 2
a * b
d = [1,2,3]
s = 'This is a string'
vec= b*d
neat = sqrt(vec)
Save the script with the name firsttest. (MATLAB with save it with an m extension, i.e., firsttest.m. That's why they're called M-files.) Then in the the command window, type firsttest just as if it were a MATLAB command. MATLAB executes all of the statements in the file (except the comment lines that are preceded with the % symbol). From now on, as you work through the exercises in this book and complete the first few assignments, you will probably find it easier to put all the commands into an M-file and then run the M-file than working directly on the command line. A word of caution about working with M-files--be careful not to name your M-files the same name as a pre-existing MATLABcommand (plot3 is a common mistake). Also the names of M-files must not have spaces or dashes in the name and they must start with a letter (not a number). Numbers and underscores are ok in M-file names. Incidentally, another way to avoid repetitive strain injuries is to use the $\uparrow$ key. Using the $\uparrow$ key you can scan through the list of commands you have typed. (Try it!) This is called the command history. (Those of you that are Unix savvy will recognize this.) If you see a command you want to re-execute, just hit $\uparrow$ until it appears, then hit return. (Try it!) You can edit any of the commands in the history. For example, suppose you typed vec1=[4,3,1] but what you really wanted was vec1=[4,3,0], but you hit return before you noticed vec1 was wrong. You can simply hit the $\uparrow$ key and then edit the command and re-execute it. Try it.
next up previous contents
Next: 1.6 Controlling output Up: 1. Getting started with Previous: 1.4.1 Arrays: vectors and   Contents
Gus Hart 2005-01-28