Page 37 - Applied Numerical Methods Using MATLAB
P. 37

26    MATLAB USAGE AND COMPUTATIONAL ERRORS
           Example 5. A switch-case-end Block

            %nm119_5: example of switch-case-end block
            point = 85;
            switch floor(point/10) %floor(x): integer less than or equal to x
              case  9, grade = ’A’
              case  8, grade = ’B’
              case  7, grade = ’C’
              case  6, grade = ’D’
              otherwise grade = ’F’
            end

           2. for index = i 0:increment:i last-end Loop
           A for loop makes a block of statements executed repeatedly for a specified
           number of times, with its loop index increasing from i_0 to a number not
           greater than i_last by a specified step (increment) or by 1 if not specified.
           The loop iteration normally ends when the loop index reaches i_last, but it
           can be stopped by a break statement inside the for loop. The for loop with a
           positive/negative increment will never be iterated if the last value (i_last)of
           the index is smaller/greater than the starting value (i_0).

           Example 6. A for Loop

            %nm119_6: example of for loop
            point = [76 85 91 65 87];
            for n = 1:length(point)
               if point(n) >= 80,  pf(n,:) = ’pass’;
                 elseif point(n) >= 0, pf(n,:) = ’fail’;
                 else  %if point(n)< 0
                 pf(n,:) = ’????’;
                 fprintf(’\n\a Something wrong with the data??\n’);
                 break;
               end
            end
            pf


           3. while Loop
           A while loop will be iterated as long as its predefined condition is satisfied and
           a break statement is not encountered inside the loop.
           Example 7. A while Loop

            %nm119_7: example of while loop
            r=1;
            whiler<10
              r = input(’\nType radius (or nonpositive number to stop):’);
              if r <= 0, break, end %isempty(r)|  r <= 0, break, end
              v = 4/3*pi*r*r*r;
              fprintf(’The volume of a sphere with radius %3.1f  = %8.2f\n’,r,v);
            end
   32   33   34   35   36   37   38   39   40   41   42