If vs Switch Case
15 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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
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 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!