# MATLAB Basics: ‘Switch case’ vs. ‘If elseif’ 28

Posted by **Doug Hull**,

This three minute video takes a look at the “Switch case” flow control statement and contrasts it with the more familiar “If elseif” flow control statement.

Often times, people will use an “If elseif” statement where a “Switch case” statement is going to be cleaner and easier to understand and maintain.

Other videos have been gathered here:

https://blogs.mathworks.com/pick/category/video/

Other MATLAB Basics posts have been gathered here:

https://blogs.mathworks.com/pick/category/matlab-basics/

As a cool little post script: At most places you celebrate the 100th something or other, but since this is a software company I feel I should celebrate the 64th video (2^6) and as I post this I see that it is the 18128th file on the File Exchange capturing the next power of two in the last three digits.

**Category:**- MATLAB Basics,
- PodCast,
- Video

### Note

Comments are closed.

## 28 CommentsOldest to Newest

**1**of 28

**2**of 28

**3**of 28

**4**of 28

**5**of 28

**6**of 28

**7**of 28

**8**of 28

**9**of 28

**10**of 28

**11**of 28

**12**of 28

**13**of 28

**14**of 28

**15**of 28

**16**of 28

**17**of 28

**18**of 28

While 1 do something endThe boolean in the while statement is ALWAYS true, that is why you never leave the loop. Doug

**19**of 28

d = 1:0.1:2 for h = 1:length(d) if d(h)(1,:)&it 1.500 alpha = 2 else alpha = 4 end k(h)(1,:) = d(h)(1,:)^2 endThank you, your help will be much appreciated.

**20**of 28

d = 1:0.1:2; % Create a "logical mask" smallEnough = d < 1.5; % Raise all elements of d to the 3rd power k = d.^3; % Square those elements that are "small enough" using the mask k(smallEnough) = d(smallEnough).^2;If you want alpha to be a vector the same size as d you can do what I did above (predefine it to be a vector of the same size as d with a "default" value then fill in certain elements to override that default) or you can do something slightly different:

alpha = zeros(size(d)); alpha(smallEnough) = 2; alpha(~smallEnough) = 4;Note that I negated the smallEnough mask to set elements of alpha corresponding to those elements of d that were NOT smallEnough to 4. You can also AND (&) or OR (|) those logical masks together to form more complicated masks for use with logical indexing.

**21**of 28

**22**of 28

**23**of 28

**24**of 28

**25**of 28

**26**of 28

**27**of 28

**28**of 28

## Recent Comments