MATLAB: If vs Switch Case

if statementswitch case

I just started coding earlier this year, and I am trying to figure out when to use certain functions. I currently have a series of 9 if/else statements, and I was wondering if it would be more efficient or if there is a reason to use switch/case over my current if else statements. P is a 9x9x9 3D matrix and C[] is a 3×3 matrix
if true
% code
if (1<= i && i<=3) && (1<= j && j<=3)
f = ismember(P(j,k,i),C1);
elseif (1<= i && i<=3) && (4<= j && j<=6)
f = ismember(P(j,k,i),C2);
elseif (1<= i && i<=3) && (7<= j && j<=9)
f = ismember(P(j,k,i),C3);
elseif (4<= i && i<=6) && (1<= j && j<=3)
f = ismember(P(j,k,i),C4);
elseif (4<= i && i<=6) && (4<= j && j<=6)
f = ismember(P(j,k,i),C5);
elseif (4<= i && i<=6) && (7<= j && j<=9)
f = ismember(P(j,k,i),C6);
elseif (7<= i && i<=9) && (1<= j && j<=3)
f = ismember(P(j,k,i),C7);
elseif (7<= i && i<=9) && (4<= j && j<=6)
f = ismember(P(j,k,i),C8);
else
f = ismember(P(j,k,i),C9);
end
if f == 1
P(j,k,i) = 0;
end

Best Answer

The only difference between if ... elsif and switch ... case is one of clarity. It shouldn't make much difference in term of performance. switch ... case is less verbose than if ... elseif but can only apply when you're comparing a single variable or expression to a set of possible values.
In your particular, the conditional expression changes all the time so it would be difficult to use a switch.