Info

此问题已关闭。 请重新打开它进行编辑或回答。

Programming course - question help

1 次查看(过去 30 天)
Mairi Robertson
Mairi Robertson 2015-10-27
关闭: MATLAB Answer Bot 2021-8-20
I am doing an 'Introduction to MATLAB' course, and one of our tasks is the following:
Write a function called generationXYZ 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, as in: gen = 'X'.
X = 1966-1980
Y = 1981-1999
Z = 2000-2012
I have written the following function:
function generationXYZ(n)
if 0 <= n && n <= 1966
fprintf('O\n')
elseif 1966 <= n && n <= 1980
fprintf('X\n')
elseif 1981 <= n && n <= 1999
fprintf('Y\n')
elseif 2000 <= n && n <= 2012
fprintf('Z\n')
elseif n >= 2013
fprintf ('K\n')
else
fprintf ('Year of birth must be greater than 0\n')
end
However when I run the grader, I am marked incorrectly because:
Feedback: Your function made an error for argument(s) 1965
But when I input 1965 as the argument to my function, the output is O, which is correct?
Anyone have any idea where I might be going wrong?
Thank you!

回答(3 个)

Stephen23
Stephen23 2015-10-27
编辑:Stephen23 2015-10-27
You are printing some text in the command window using fprintf. The task you were given is not to print text into the command window, but to return a string as an output argument from the function.
You can do this by defining the output variable in the function definition:
function out_string = generationXYZ(n)
and define the variable out_string inside your function.
  2 个评论
Mairi Robertson
Mairi Robertson 2015-10-27
Forgive me for being so stupid but I really am just a beginner. How to I define the variable inside my function? Thanks
Stephen23
Stephen23 2015-10-27
编辑:Stephen23 2015-10-27
Define a variable using an equals sign and the variable name on the left:
X = 3;
where X is the variable name that you want to use, and the 3 is the value to assign to it. This value could be string:
Y = 'cat';
I would highly recommend that you work through the introductory tutorials, which are a great way to learn basic MATLAB concepts and usage:
and maybe read this:

Walter Roberson
Walter Roberson 2015-10-27
Return as output, not print!

Thorsten
Thorsten 2015-10-27
Define your function with an output argument
function s = generationXYZ(n)
and assign this in your function
if 0 <= n && n <= 1966
s = 'O';
else ... % change other lines accordingly

此问题已关闭。

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by