Are statements in a Switch-expression necessary?

This is my code:
for welke_pp=1:aantal_pp
switch welke_pp
case 1
case 2
case 3
case 4
case 5
end
...
I started a for-loop for 5 subjects. Then I switch them by case 1,2,3,4 and 5. Because the whole for-loop is completely the same for each subject (except for the selected data), I wonder if 'statements' under each 'case-expression' are really necessary for my program?

6 Comments

Sam - what would you use the if statements for? Are you being asked in your assignment/homework to use if statements?
The assignment is to make a program for 5 subjects, which each have 5 measurements (so 5x5). I've made a for-loop for 1 subject who calculate everything for the 5 measurements. Now I created a switch-expression so that it changes to the next subject, subject 2. And so on. I'm free the use everything in Matlab.
So you could add an outer for loop for the subjects with the inner for loop (as above) just for the measurements.
Yes, I've done this already. The outer for-loop is the 'welke_pp=1:aantal_pp'. This is for the 5 subjects. I've already created an inner for-loop for the measurements. But I was wondering if it is necessary to write a statement behind every case-expression.
No, but in that case there's no need for the specific case either
You seem to be misunderstanding the purpose of a switch statement. If the cases are empty, the entire statement does absolutely nothing. The empty switch statement you have is equivalent to:
if welke_pp==1
elseif welke_pp==2
elseif welke_pp==3
elseif welke_pp==4
elseif welke_pp==5
end
You seem to be implying that you think that the switch statment itself is actually changing welke_pp. It doesn't... that is handled by the for loop. The switch statement only looks at the value of welke_pp and performs an action depending on what value it sees (the cases).

Sign in to comment.

Answers (1)

You can have a case without any statement, but there is no point writing that specific case in the first place, unless you also have an otherwise. The otherwise catches all the values that have not been dealt with a particular case. You can also regroup case values together if the statements are the same:
switch welke_pp
case 1 %handle value 1
do_fun;
case {2, 3} %handle value 2 and 3
do_otherfun;
case 4 %handle value 4
%does nothing
otherwise %handle all other values
do_somethingelse;
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

Sam
on 20 Dec 2014

Commented:

on 20 Dec 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!