Page 60 - A Guide to MATLAB for Beginners and Experienced Users
P. 60

Presenting Your Results      41


                     Judging from the output, you can expect to find the answer to the question we
                     posed above by typing sinelimit(10). Try it!


           Loops


                     A loop specifies that a command or group of commands should be repeated
                     several times. The easiest way to create a loop is to use a for statement. Here
                     is a simple example that computes and displays 10! = 10 · 9 · 8 ··· 2 · 1:

                       f=1;
                       for n = 2:10
                            f = f*n;
                       end
                       f
                     The loop begins with the for statement and ends withthe end statement. The
                     command between those statements is executed a total of nine times, once for
                     eachvalue of n from 2 to 10. We used a semicolon to suppress intermediate
                     output within the loop. To see the final output, we then needed to type f after
                     the end of the loop. Without the semicolon, MATLAB would display each of
                     the intermediate values 2!, 3!, ... .
                       We have presented the loop above as you might type it into an M-file; inden-
                     tation is not required by MATLAB, but it helps human readers distinguish the
                     commands within the loop. If you type the commands above directly to the
                     MATLAB prompt, you will not see a new prompt after entering the for state-
                     ment. You should continue typing, and after you enter the end statement,
                     MATLAB will evaluate the entire loop and display a new prompt.
                     If you use a loop in a script M-file with echo on in effect, the commands will
                       be echoed every time through the loop. You can avoid this by inserting the
                       command echo off just before the end statement and inserting echo on
                       just afterward; then each command in the loop (except end) will be echoed
                       once.


           Presenting Your Results



                     Sometimes you may want to show other people the results of a script M-file
                     that you have created. For a polished presentation, you should use an M-book,
                     as described in Chapter 6, or import your results into another program, such
   55   56   57   58   59   60   61   62   63   64   65