function using if or switch statement
Show older comments
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....
Accepted Answer
More Answers (1)
Walter Roberson
on 20 May 2015
0 votes
The expression 1966<=n<=1980 is interpreted as ((1966<=n)<=1980) . The first subpart of that, (1966<=n), returns a logical value, 0 for false and 1 for true. That value is then tested against <= 1980 and since 0 and 1 are both <= 1980, the result is always true.
You need 1966 <= n && n <= 1980
You also need to look more carefully at how you are treating the exact year 1966 and how you are treating the exact year 2012
4 Comments
Muhammad Usman Saleem
on 20 May 2015
Edited: Walter Roberson
on 20 May 2015
Muhammad Usman Saleem
on 20 May 2015
Walter Roberson
on 20 May 2015
if 2012 > n then n < 2012 so that test is checking for dates before 2012.
Note: there is no reason to keep checking 1966. Test 1966 first, and if that is false then you know the value must be at least 1966 and need not test against 1966 again.
Muhammad Usman Saleem
on 20 May 2015
Categories
Find more on Software Development in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!