MATLAB: Function using if or switch statement

if statementMATLABmatlab functionswitch statement

I am going to make a function called XYZ that takes as its only input argument one positive integer specifying the year of birth of a person and returns as its only output argument the name of the generation that the person is part of ('X', 'Y', or 'Z ') according to the table below. For births before 1966, return 'O' for Old and for births after 2012, return 'K' for Kid . Remember that to assign a letter to a variable, you need to put it in single quotes,
I have make that code
function born=generationXYZ(n)
if 1966<=n<=1980
born='X';
end
if 1981<=n<=1999
born='Y';
end
if 2000<=n<=2012
born='Z';
end
if n<=1966
born='O';
end
if n=>2012
born='K';
end
end
but when i test this code i getting an error when i remove last two if check i always recipe z in output.
I know it can make with switch statement kindly refer me where i need corrections. Thanks in advance for assistance….

Best Answer

To fix your code, use Walter's answer.
You call also altogether avoid if or switch and use:
function born = generationXYZ(n)
bins = [-Inf, 1966, 1981, 2000, 2013, +Inf]; %as Walter pointed out some of your edges are ambiguous
gennames = 'OXYZK#'; %return # if input is +Inf
born = gennames(discretize(n, bins));
end
This also has the advantage that it also works for vectors