Which is faster: using a switch statement or using a nested if else? Write a script to test this
belongs to book: MATLAB: A Practical Introduction to Programming and Problem Solving|Stormy Attaway|Fourth Edition| Chapter number:5| Question number:35.5
All Answers
total answers (1)
Ch5Ex35.m
% Test which is faster: switch or nested if-else
fprintf('First for if-else\n\n')
tic
for i = 1:1000
for j = 1:4
if j == 1
result = 11;
elseif j == 2
result = 22;
elseif j == 3
result = 46;
else
result = 6;
end
end
end
toc
fprintf('Now switch\n\n')
tic
for j = 1:1000
for k = 1:4
switch k
case 1
res = 11;
case 2
res = 22;
case 3
res = 46;
otherwise
res = 6;
end
end
end
toc
need an explanation for this answer? contact us directly to get an explanation for this answer