Q:

Which is faster: using a switch statement or using a nested if else? Write a script to test this

0

Which is faster: using a switch statement or using a nested if else? Write a script to test this.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

total answers (1)

Similar questions


need a help?


find thousands of online teachers now