ROCK = 1; PAPER = 2; SCISSORS = 3; if p1 == ROCK if p2 == PAPER winner = 2; elseif p2 == SCISSORS winner = 1; else winner = 0; end elseif p1 == PAPER if p2 == ROCK winner = 1; elseif p2 == SCISSORS winner = 2; else winner = 0; end else % p1 == SCISSORS if p2 == ROCK winner = 2; elseif p2 == PAPER winner = 1; else winner = 0; end end
for i = [4 9 16 20 24 36 49] if rem(sqrt(i), 1) ~= 0 break end disp(sqrt(i)) end for i = [4 9 16 20 24 36 49] if rem(sqrt(i), 1) ~= 0 continue end disp(sqrt(i)) end
General syntax:
switch expression case value1 statements case value2 statements ... otherwise statements end
Example: Rock-Paper-Scissors revisited
ROCK = 1; PAPER = 2; SCISSORS = 3; switch p1 case ROCK switch p2 case PAPER winner = 2; case SCISSORS winner = 1; case ROCK winner = 0; end case PAPER switch p2 case ROCK winner = 1; case SCISSORS winner = 2; case PAPER winner = 0; end case SCISSORS switch p2 case ROCK winner = 2; case PAPER winner = 1; case SCISSORS winner = 0; end end
Example:
choice = input('Yes or no? (y/n) ', 's'); switch choice case {'Y', 'y'} disp('yes') case {'N', 'n'} disp('no') otherwise disp('unknown choice') end