478 Chapter 15 MATLAB
The M-file
As explained previously, for simple operations you can use MATLAB’s Command Window to
enter variables and issue commands. However, when you write a program that is more than a
few lines long, you use an M-file. It is called an M-file because of its .mextension. You can cre-
ate an M-file using any text editor or using MATLAB’s Editor/ Debugger. To create an M-file,
open the M-file Editor by going to File SSNew SSBlank M-File, and MATLAB opens a new
window in which you can type your program. As you type your program, you will notice that
MATLAB assigns line numbers in the left column of the window. The line numbers are quite
useful for debugging your program. To save the file, simply click File SSSaveAs...and type
in the file-name. The name of your file must begin with a letter and may include other char-
acters such as underscore and digits. Be careful not to name your file the same as a MATLAB
command. To see if a file-name is used by a MATLAB command, type exist (‘file-name’)in
the MATLAB’s Command Window. To run your program, click on Debug SSSave File and
Run(or use the function key F5). Don’t be discouraged to find mistakes in your program the
first time you attempt to run it. This is quite normal! You can use the Debugger to find your
mistakes. To learn more about debugging options, type help debugin the MATLAB Command
Window.
Example 15.3 It has been said that when Pascal was 7 years old, he came up with the formula to
determine the sum of 1, 2, 3,... , through n. The story suggests that one day he was asked by
his teacher to add up numbers 1 through 100, and Pascal came up with the answer in few
minutes. It is believed that Pascal solved the problem in the following manner:
First, on one line he wrote the numbers 1 through 100, similar to
1234........... 99100
Then, on the second line he wrote the numbers backward
100 99 98 97........... 2 1
Then, he added up the numbers in the two lines, resulting in one hundred identical values
of 101
101 101 101 101........... 101 101
Pascal also realized that the result should be divided by 2 — since he wrote down the numbers
1 through 100 twice — leading to the answer: Later, he generalized his
approach and came up with the formula
n 1 n 12
2
.
10011012
2
5050.
n 1 n 12
2
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
圀圀圀⸀夀䄀娀䐀䄀一倀刀䔀匀匀⸀䌀伀䴀圀圀圀⸀夀䄀娀䐀䄀一倀刀䔀匀匀⸀䌀伀䴀