Page 22 -
P. 22

1.5  MATLAB Simple Programming

                             1.5.1  Iterative Loops
                             The power of computers lies in their ability to perform a large number of
                             repetitive calculations. To do this without entering the value of a parameter
                             or variable each time that these are changed, all computer languages have
                             control structures that allow commands to be performed and controlled by
                             counter variables, and MATLAB is no different. For example, the MATLAB
                             “for” loop allows a statement or a group of statements to be repeated.

                             Example 1.8
                             Generate the square of the first ten integers.

                             Solution: Edit and execute the the following script M-file:

                                for m=1:10
                                x(m)=m^2;
                                end;
                             In this case, the number of repetitions is controlled by the index variable m,
                             which takes on the values m = 1 through m = 10 in intervals of 1. Therefore, ten
                             assignments were made. What the above loop is doing is sequentially assign-
                             ing the different values of m^2 (i.e., m ) in each element of the “x-array.” An
                                                              2
                             array is just a data structure that can hold multiple entries. An array can be
                             1-D such as in a vector, or 2-D such as in a matrix. More will be said about
                             vectors and matrices in subsequent chapters. At this time, think of the 1-D
                             and 2-D arrays as pigeonholes with numbers or ordered pair of numbers
                             respectively assigned to them.
                              To find the value of a particular slot of the array, such as slot 3, enter:
                                x(3)

                             To read all the values stored in the array, type:

                                x

                             Question: What do you get if you enter m?


                             1.5.2  If-Else-End Structures
                             If a sequence of commands must be conditionally evaluated based on a rela-
                             tional test, the programming of this logical relationship is executed with
                             some variation of an if-else-end structure.


                             © 2001 by CRC Press LLC
   17   18   19   20   21   22   23   24   25   26   27