If vs Switch Case

조회 수: 13 (최근 30일)
Mike  M
Mike M 2015년 3월 11일
댓글: Guillaume 2015년 3월 11일
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 3x3 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

채택된 답변

Guillaume
Guillaume 2015년 3월 11일
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.
  댓글 수: 1
Guillaume
Guillaume 2015년 3월 11일
However, you could avoid the entire if or switch with:
C = {C1 C2 C3 C4 C5 C6 C7 C8 C9}; %assuming the Cs are vectors
lowerthresh = [1 4 7];
higherthresh = [3 6 9];
cidx = (find(i >= lowerthresh & i <= higherthresh) - 1) * 3 + find(j >= lowerthresh & j <=higherthresh);
%note this assumes that i and j are always between one of these bands
f = ismember(P(j, k, i), C{cidx});
It remains to be seen if it's more efficient that the if.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Language Fundamentals에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by