Sunday, May 5, 2024

SWITCH, BREAK, CONTINUE STATEMENTS IN MATLAB

Must read

SWITCH:

Where in switch case from available number of alternative it execute one set of statement. In this each alternative is considered as a case, switch can handle multiple conditions in a single case statement by enclosing the case expression in a cell array.

This includes the phrase in any other case, observed with the aid of using the statements to execute if the expression’s cost isn’t treated with the aid of using any of the previous case groups.

In its fundamental syntax, switch executes the statements related to the primary case wherein case. When the case expression is a cell array (as with inside the second case above), the case suits if any of the factors of the cell array suits the transfer If no case expression suits the switch expression, then manipulate passes to the in any other case. After the case is executed, application execution resumes with the assertion after the end. If the first case is true then it does not execute next state. So, break statement does not required.

Switch statements

 Case cost1

         Declarations     % executes if statements is cost1

Case cost 1

         Declarations         % executes if statements is cost 2

Otherwise

         Declarations            % executes if statements does not match any case

End

For example let consider to execute a certain block of code based on what the string ‘color’ is set to:

color = ‘rose’;

switch lower(color)
   case {‘red’, ‘light red’, ‘rose’}
      disp(‘color is red’)

   case ‘blue’
      disp(‘color is blue’)

   case ‘white’
      disp(‘color is white’)

   otherwise
      disp(‘Unknown color.’)
end

BREAK:

Break statements is used to exist early from for and while loops. Where in nested loop break is used only for inner loop only, after the execution of the break statement control passes statements that follow the end of that loop. For nested loop if we use break statement only it stop executing inner loop, not outer loop, control passes statements  that follow the end of that loop.

Let’s consider an example:
y = [-2 -4 0 -4 3 7];

% let us test each element with some special condition
for i = 1 : length(z)

   % let we test for the given condition which is  greater-than-zero value
   if z(i) > 0
      %  let we terminates the loop execution
      break
   end
   y = z(i) + 5;
   disp(y)
  
end

CONTINUE:

Continue statement temporary interrupts the program execution loop, skipping any given remaining statements in the body of the loop and continues with the current pass. Let’s consider an example. % Let’s us consider an example and execute the example based on assumption that you are verifying a set of values.
for i = 1: 9
if (i == 2 | i == 3)
    continue
end

  % here we can continue with the remaining values,
  disp (i)

end

Previous article
Next article
- Advertisement -

More articles

- Advertisement -

Latest article