CaptainProg
CaptainProg

Reputation: 5690

Non-breaking switch statements

I understand that in MATLAB it is not necessary (as it is in C++) to end each 'case' of a switch statement with a 'break;'. The statement stops evaluating once it finds the first successful case.

However, I have the following situation:

switch variable
    case {0, 1}
        % Action A
    case {0, 2}
        % Action B
end

In the above situation, if 'variable' equals 0, then only Action A will complete. In the case of variable = 0, I'd like both actions to complete. I could make a separate case for 0 which activates both Actions A & B, but that hardly seems like efficient programming as I'd have to duplicate both the actions.

I'm sure there must be a simple way to do this, but I'm still a relative newbie to MATLAB so I wonder what I could do to keep my code tidy?

Regards

Upvotes: 3

Views: 4299

Answers (3)

Eitan T
Eitan T

Reputation: 32930

The MATLAB switch statement unfortunately does not provide the flexibility of fall-through logic, so you won't be able to use it in this case.

You could replace the switch with successive if statements (accompanied by a few comments) and this is what you'd get:

%# Switch variable
if (variable == 0 || variable == 1)  %# case {0, 1}
   %# Action A
end
if (variable == 0 || variable == 2)  %# case {0, 2}
   %# Action B
end

and it would still look elegant in my opinion.

Upvotes: 7

Peter
Peter

Reputation: 14937

Code length is not necessarily the same as readability or efficiency. I would argue that the right answer is to discard the switch and just write what you mean:

if((variable == 0) || (variable == 1))
  ActionA();
end

if((variable == 0) || (variable == 2))
  ActionB();
end

Upvotes: 6

Chris
Chris

Reputation: 46316

You state

I could make a separate case for 0 which activates both Actions A & B, but that hardly seems like efficient programming as I'd have to duplicate both the actions.

Regardless of efficiency, this is probably the most readable thing to do. I would always go for readability until you can prove that some piece of code is a bottleneck. So I would write:

switch variable
    case 0
        ActionA()
        ActionB()
    case 1
        ActionA()
    case 2
        ActionB()
end

function ActionA()
    ...
end

function ActionB()
    ...
end

If you really want a non-breaking switch you can follow the advice from a MATLAB Central blog post on the switch statement:

To achieve fall-through behavior in MATLAB, you can specify all the relevant expressions in one case and then conditionally compute values within that section of code.

Upvotes: 2

Related Questions