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

Branching       103


                       function y = absval(x)
                       y=x;
                       ify<0
                            y = -y;
                       end

                       The elseif statement is useful if there are more than two alternatives
                     and they can be distinguished by a sequence of true/false tests. It is essen-
                     tially equivalent to an else statement followed immediately by a nested if
                     statement. In the example below, we use elseif in an M-file signum.m, which
                     evaluates the mathematical function
                                     
                                      1    x > 0,
                            sgn(x) =    0   x = 0,
                                      −1    x < 0.
                                     
                     (Again, MATLAB has a built-in function sign that performs this function for
                     more general inputs than we consider here.)


                       function y = signum(x)
                       ifx>0
                            y=1;
                       elseif x == 0
                            y=0;
                       else
                            y = -1;
                       end

                     Here if the input x is positive, then the output y is set to 1 and all commands
                     from the elseif statement to the end statement are skipped. (In particular,
                     the test in the elseif statement is not performed.) If x is not positive, then
                     MATLAB skips to the elseif statement and tests to see if x equals 0.Ifso, y is
                     set to 0; otherwise y is set to -1. Notice that MATLAB requires a double equal
                     sign == to test for equality; a single equal sign is reserved for the assignment
                     of values to variables.

                     Like for and the other programming commands you will encounter, if and
                       its associated commands can be used in the Command Window. Doing so can
                       be useful for practice with these commands, but they are intended mainly for
                       use in M-files. In our discussion of branching, we consider primarily the case
                       of function M-files; branching is less often used in script M-files.
   117   118   119   120   121   122   123   124   125   126   127