Write a function called under_age that takes two positive integer scalar arguments: age that represents someone's age, and limit that represents an age limit. The function returns true if the person is younger than the age limit. If the second arg

142 visualizaciones (últimos 30 días)
function too_young = under_age(age,limit)
limit = 21
if age <= limit
too_young = true;
elseif age >= limit
too_young = false;
else
fprintf('invalid\n')
end
  16 comentarios
Jan
Jan el 4 de Abr. de 2022
This has become a strange thread. We find a pile of suboptimal implementations.
We need 6 lines of code (including the trailing "end"). John has condensed the IF block into 1 line, but without doubt his implementation is clean and exhaustive.
So what is the reason to post a lot of other less elegant and not working versions?
Many beginners suggest:
if limit > age
too_young = true;
else
too_young = false;
end
instead of the compact and efficient:
too_young = limit > age;
DGM
DGM el 21 de Feb. de 2023
Editada: DGM el 4 de Dic. de 2023
Sometimes when clearing out tangled dry underbrush, one is overcome with a profound appreciation for the simple elegance of fire. I think I'd better take a break.
If future me (or anyone else) wants to pick up where I left off, here are my notes on a subset of the answers which very closely follow a common form:
378292 the first of the type, has extra return statement, inconsistent indentation
380788 has extraneous ()
427771 randomly indented
428601 indented, but otherwise identical to 427771
423954 all variable names are replaced with letters
442503 has extra isempty() test, logic is flipped but correct
446375 identical to 428601 excepting whitespace (includes console dump)
477187 identical to 428601 excepting whitespace
477322 trying too hard to say "it's totally different"
478066 identical to 428601 excepting whitespace and unused code as comments
1074038 identical to 428601 excepting whitespace and a comment that says "the shortest way"
EDIT: these also constitute a set of trivial variations of a common answer:
Find the ones that look the most like copypasta, see if user posted other answers, find more threads full of samey copypasta, fall down rabbit hole.

Iniciar sesión para comentar.

Respuesta aceptada

John D'Errico
John D'Errico el 23 de Mzo. de 2019
Editada: John D'Errico el 8 de Nov. de 2020
This is not an error. It is a failure of your code to work as it is supposed to work by your goals.
What did I say? What has EVERYONE said so far? You cannot set a default as you did.
Even though you pass in the number 18 as the limit, the first thing you do inside is reset that value to 21.
Instead, you need to think about how to test to see if limit was provided at all.
Edit: (18 months later)
Now that there are dozens of answers, all of which are lengthy, I'll show how I would write it.
function tooyoung = under_age(age,limit)
% under_age: returns true if the person is under the age limit
% usage: tooyoung = under_age(age,limit)
%
% Arguments: (input)
% age - numeric. As written, age can be scalar, or any size array
%
% limit - optional argument, if not provided, the default is 21
%
% arguments: (output)
% tooyoung - a boolean variable, indicating if age was under the limit.
%
% NO tests are done to verify that age or limit, if provided are valid
% ages itself, or even if they is numeric at all. Better code would
% do these things.
% test for limit having been provided. if not, then the default is 21
if nargin < 2, limit = 21; end
% There is no need to use an if statement. The test itself is the desired result.
tooyoung = age < limit;
end
See that most of my code was actually comments. Help is hugely important, since it allows you to quickly use the code next year when you forget how it was written, or when you forget what the arguments mean.
Think of internal comments as reminders to yourself, for a year from now when you look at the code and need to change the code for some reason, or god forbid, you need to debug it. My recommended target is one line of comment per line of code, or at worst, one line of code per significant thing done in the code.
Comments are free! Good code should look positively green due to all of the comments. My solution code was lengthy only because of all of the comments.
What else?
Remember that white space is hugely important. It makes your code easy to read.
Use intelligent, meaningful variable names. Good mnemonic variable names help to make your code self-documenting, and again, easy to read. When you are scanning through the code, you don't want to continuously go back and be forced to remember what does the variable wxxyy do?
As I said, better code would have included tests to verify that both age and limit, if provided, were actually numeric variables. The best code is friendly code. When it fails, you want the code to fial in a friendly way, telling the person what was seen to be wrong. What you don't want to happen is the code does something screwy and unexpected, or returns some random difficult to understand error message. The best code makes it easy to use that code.
The final test in this code is a vectorized test, in that if you called the code like this:
tooyoung = under_age([12 5 29 75],21)
tooyoung =
1 1 0 0
it will work and return a vector of results. Vectorized code is generally good code, since it allows the user to not be forced to use a loop when they want to use the code many times in a row.
Finally, could I have written code that would have required only one line of code? Thus testing to see if limit was provided, and returning a comparison to age in just one line? Probably, but that would have been unnecessarily complicated, difficult to read and debug. There would have been no gain in the quality of the code or how fast it runs. Good code is simple, easy to read, easy to use, easy to debug.
  5 comentarios
Rik
Rik el 5 de Ag. de 2020
Have you read the documentation for the nargin function to see what it does? It returns the n[umber of] arg[uments you provide as] in[put]. So if it is smaller than 2, that means the limit was not provided as an input argument.

Iniciar sesión para comentar.

Más respuestas (26)

Saurabh Kumar
Saurabh Kumar el 28 de Mzo. de 2019
Write a function called under_age that takes two positive integer scalar arguments:
  1. age that represents someone's age, and
  2. limit that represents an age limit.
The function returns true if the person is younger than the age limit. If the second argument, limit, is not provided, it defaults to 21. You do not need to check that the inputs are positive integer scalars.
function x = under_age(age,limit)
if nargin < 2
limit = 21;
if age < limit
x = true;
else
x = false;
end
end
if nargin == 2
if age < limit
x = true;
else
x = false;
end
end
  7 comentarios
Quyen Le
Quyen Le el 20 de Jun. de 2021
Ofc I tried your answer and it worked. but i would want to understand clearly
Walter Roberson
Walter Roberson el 20 de Jun. de 2021
MATLAB (and nearly all programming languages... but not all) are Procedural Languages, in which the order of statements is important.
Suppose you were climbing a ladder. For the most part, you take one step upward at a time. Now suppose you program it that way,
"Move foot 50 cm higher and put weight on it"
But what about when you get to the top?
"Move foot 50 cm higher and put weight on it"
"If there was no higher rung, don't take that step"
Too late. You already put your weight in mid-air before checking whether there was something to put your weight onto.
You instead need a check like
"If there is a higher rung, move foot 50 cm higher and put weight on it"
Check first, before relying on it being there.
The way you coded
if age < limit
if nargin < 2
limit = 21
end
end
is similar to not having checked for a higher rung existing before putting your weight where it would be.
===
It is better programming practice to check for exceptions first, check to see whether a calculation is going to be valid before doing the calculation.
However, there are some situations in which it is valid to "patch up" if you encounter an exception. For example, better programming practice for "1/x if x is not 0, 0 if x is 0" would be
y = zeros(size(x));
mask = x ~= 0;
y(mask) = 1./x(mask);
This code never does any division by 0.
But if you are sure you are using IEEE 754, you can count on the fact that IEEE 754 defines that 1/x has some result for 1/0 (rather than crashing the program), and you can instead do a patch-up-later version:
y = 1./x;
y(x == 0) = 0;
The patch-up-later version of the question would be like,
function too_young = under_age(age, limit)
too_young = age < 21;
if nargin > 1
too_young = age < limit;
end
end
Notice that the variable limit is not used until after it has been checked to be sure that it is present.

Iniciar sesión para comentar.


Astr
Astr el 8 de Sept. de 2019
function too_young = under_age(age, limit)
if nargin == 1
limit = 21;
end
too_young = gt(limit, age);

mayank ghugretkar
mayank ghugretkar el 7 de Jun. de 2019
this can work too...
A bit compact approach
function too_young = under_age(age, limit)
if nargin < 2
limit = 21;
end
if age < limit
too_young=true;
else
too_young=false;
return
end
end
  5 comentarios
Karina Medina Barzola
Karina Medina Barzola el 3 de Jun. de 2021
nargin is a variable? if i change it to an another variable, it sent me an error. what nargin is. Thanks
Rik
Rik el 3 de Jun. de 2021
help nargin
NARGIN Number of function input arguments. Inside the body of a user-defined function, NARGIN returns the number of input arguments that were used to call the function. If the function uses an arguments validation block, then only positional arguments provided by the function call are included in this number. Optional arguments not provided by the caller are not included. Name-value arguments are never included, whether provided or not. NARGIN(FUN) returns the number of declared inputs for the function FUN. The number of arguments is negative if the function has a variable number of input arguments. If the function uses an arguments validation block, NARGIN returns the number of declared positional arguments on the function line as a nonnegative value. FUN can be a function handle that maps to a specific function, or a character vector or string scalar that contains the name of that function. See also NARGOUT, VARARGIN, NARGINCHK, INPUTNAME, MFILENAME. Documentation for nargin doc nargin Other functions named nargin fittype/nargin inline/nargin

Iniciar sesión para comentar.


Nijita Kesavan Namboothiri
Nijita Kesavan Namboothiri el 25 de Jun. de 2019
function too_young= under_age(age, limit)
if (nargin<2)
limit=21;
end
if (age<limit)
too_young=true
else
too_young=false
end
end
  6 comentarios
Kilaru Venkata Krishna
Kilaru Venkata Krishna el 2 de Mayo de 2020
function too_young = under_age(age,limit);
if (nargin<2)
limit=21;
end
if age < limit
too_young=true;
else age >= limit
too_young=false;
end

Iniciar sesión para comentar.


Siddharth Joshi
Siddharth Joshi el 23 de Abr. de 2020
function too_young = under_age(age,limit)
if nargin<2
limit=21;
end
if age<limit
too_young=true;
else
too_young=false;
end
end
too_young = under_age(18,18)
too_young = under_age(20)
too_young =
logical
0
too_young =
logical
1

sudeep lamichhane
sudeep lamichhane el 27 de Abr. de 2020
function too_young = under_age(age, limit)
if nargin<2
limit=21;
end
if age < limit
too_young= true;
else
too_young= false;
end

Sai Hitesh Gorantla
Sai Hitesh Gorantla el 1 de Feb. de 2020
Editada: Rik el 17 de Jun. de 2020
function [too_young] = under_age(age,limit)
if nargin == 2
if age<limit
too_young = true;
else
too_young = false;
end
elseif nargin<2
if age<=21
too_young = true;
else
too_young = false;
end
end

mohammad elyoussef
mohammad elyoussef el 4 de Abr. de 2020
function c = under_age(a,b)
if nargin < 2
b = 21;
end
if b > a
c = true;
else
c = false;
end

maha khan
maha khan el 9 de Abr. de 2020
function [too_young]= under_age(age,limit)
if (nargin < 2) || isempty(limit)
limit = 21;
end
if age>21
too_young=false;
elseif age < limit
too_young=true;
elseif age==age
too_young=false;
elseif age<=21
too_young=true;
elseif age < age
too_young=false;
elseif age<=21
too_young=true;
else
too_young=true;
end
  1 comentario
Walter Roberson
Walter Roberson el 9 de Abr. de 2020
Suppose the user passes in a limit of 35, such as testing for eligibility to be President of the United States. And suppose the age passed in is 29. Then if age>21 would be if 29>21 and that would be true, so you would declare too_young=false but clearly the answer should be true: 29 < the specified limit.

Iniciar sesión para comentar.


Mir Mahim
Mir Mahim el 7 de Mayo de 2020
function a = under_age(age,limit)
if nargin < 2
limit = 21;
end
a = age < limit;
end

Aasma Shaikh
Aasma Shaikh el 26 de Mayo de 2020
function too_young= under_age (age, limit)
if nargin<2
limit=21;
if (age<limit)
too_young = true;
else
too_young = false;
end
elseif ((nargin==2) && (age<limit))
too_young = true;
else
too_young = false;
end
end
% Copy, paste and Run

jaya shankar veeramalla
jaya shankar veeramalla el 29 de Mayo de 2020
function too_young = under_age(age,limit)
if (nargin < 2) || isempty(limit)
limit = 21;
end
if age < limit
too_young = true;
else age >= limit
too_young = false;
end

AYUSH MISHRA
AYUSH MISHRA el 4 de Jun. de 2020
function too_young =under_age(age,limit)
if nargin <2
limit=21;
end
if age<limit
too_young=true;
else
too_young=false;
end
SOLUTION ;
under_age(18,18)
ans =
logical
0
under_age(20)
ans =
logical
1

Keshav Patel
Keshav Patel el 8 de Jun. de 2020
function too_young =under_age(age,limit)
if nargin<2
limit=21;
if age<limit
too_young=true;
else
too_young=false;
end
end
if nargin ==2
if age<limit
too_young=true;
else
too_young=false;
end
end

saurav Tiwari
saurav Tiwari el 17 de Jun. de 2020
Editada: Rik el 17 de Jun. de 2020
function [a]=under_age(n,m)
a=n<m;
if a==1;
fprintf('true')
end
if nargin<2;
m=21;
end
end

AKASH SHELKE
AKASH SHELKE el 9 de Ag. de 2020
Editada: AKASH SHELKE el 9 de Ag. de 2020
function too_young = under_age(age,limit)
if nargin<2
limit = 21;
end
if age < limit
too_young = true;
else
too_young = false;
end

Muhammad Akmal Afibuddin Putra
Muhammad Akmal Afibuddin Putra el 10 de Ag. de 2020
function too_young = under_age(age,limit)
if nargin < 2
limit = 21;
end
if age < limit
too_young = 1 == 1;
else
too_young = 1 ==2;
end
end
  3 comentarios
Rik
Rik el 10 de Ag. de 2020
That's a creative way to write true and false.
But why did you decide to post it? It doesn't seem to show a new strategy to solve this problem. Note that Answers is not a homework submission service.

Iniciar sesión para comentar.


Omkar Gharat
Omkar Gharat el 11 de Ag. de 2020
function [too_young] = under_age(age,limit);
% age = input('Enter age of applicant : ')
% limit = input('Enter age limit of applicant : ')
if nargin < 2
limit = 21;
end
if age < limit
too_young = true;
else
too_young = false;
end
end
This is my code .And it is 100% correct

Khom Raj Thapa Magar
Khom Raj Thapa Magar el 6 de Sept. de 2020
Make sure your indentation is correct while coding
function too_young = under_age(age,limit)
if nargin<2
limit = 21;
if age < limit
too_young = true;
else
too_young = false;
end
end
if nargin == 2
if age < limit
too_young = true;
else
too_young = false;
end
end
Calling functions
>> too_young = under_age(18,18)
>> too_young = under_age(20)
Output:
too_young =
logical
0
too_young =
logical
1

Jessica Trehan
Jessica Trehan el 21 de Sept. de 2020
function too_young=under_age(age,limit)
if nargin<2
limit=21;
if age<limit
too_young=true;
else
too_young=false;
end
end
if nargin==2
if age<limit
too_young=true;
else
too_young=false;
end
end
%THE PERFECT CODE
  7 comentarios
Rik
Rik el 11 de En. de 2021
The variable name is 'too_young'. Your code is claiming that 40 is too young if the age limit is 21. Either the variable name is misleading, or your comparator is the wrong way around.
Olha Skurikhina
Olha Skurikhina el 11 de En. de 2021
Thank you. It is very stupid. I already solved harder problems along the course but this one couldn`t tackle. That was my problem and plus if the age= limit, it is still should return false so '<=' is incorrect.

Iniciar sesión para comentar.


amjad ali
amjad ali el 6 de Sept. de 2021
function too_young=under_age(age,limit);
switch nargin
case 1
limit=21;
end
if (limit>age);
too_young=true;
else
too_young=false;
end
switch nargin
case 2
end
if limit>age ;
too_young=true;
else
too_young=false;
end
  2 comentarios
Walter Roberson
Walter Roberson el 6 de Sept. de 2021
This code fails if nargin is 0 .
This code tests the age against the limit twice, and has a useless second swtich statement that does nothing.
amjad ali
amjad ali el 6 de Sept. de 2021
thankx for your comment
i have no idea before that the second switch statement is useless,

Iniciar sesión para comentar.


VIGNESH B S
VIGNESH B S el 13 de Oct. de 2021
function [too_young] = under_age(age,limit)
if nargin == 2
too_young = compare(age,limit);
elseif nargin == 1
too_young = compare(age,21);
end
end
function [answer] = compare(x,y)
if x<y
answer = (1>0);
else
answer = (0>1);
end
end
  3 comentarios
VIGNESH B S
VIGNESH B S el 14 de Oct. de 2021
answer = 1>0 is same as declaring true .... the question too asks us about returning either true or false base on some condition... also i wanted to have functions in it to look a bit elegant.. so i just declared other function and did calculations!! thanks all no more than that ..
Image Analyst
Image Analyst el 14 de Oct. de 2021
But it doesn't look elegant. An elegant program would do
answer = x < y;
instead of the clunky
if x<y
answer = (1>0);
else
answer = (0>1);
end

Iniciar sesión para comentar.


Alexandar
Alexandar el 29 de Jun. de 2022
This worked well for me. Very short but I sort of don't understand why the "nargout" part worked.
function too_young = under_age(age, limit)
if nargin < 2
limit = 21
end
too_young = age<limit;
if nargout == 2
too_young = true(1);
end
  4 comentarios
Rik
Rik el 29 de Jun. de 2022
Why did you add those last lines? Your output is already a logical. Also, false(0) will create an empty array.
And the double = is a comparison. For the if branch that means no code is executed (and the ; is superfluous), and for the else branch that means the too_young variable is compared to an empty array. Since those aren't equal, the result of that is false. That result is not assigned to a variable, so the ; prevents you from seeing it is stored in ans.
Are you using Matlab itself to write this code? There should be several mlint warnings.
Alexandar
Alexandar el 29 de Jun. de 2022
Editada: Alexandar el 29 de Jun. de 2022
Yes, this was done for a matlab coursea assignment that said the code worked perfectly well which confused me. I started coding three weeks ago.

Iniciar sesión para comentar.


Muhammad
Muhammad el 23 de Jul. de 2022
%Help required
Error showing=Output argument "x" (and possibly others) not assigned a value in the execution with "under_age" function.
function x = under_age(age,limit)
if nargin < 2
limit=21;
if age < limit
x=true;
end
end
if nargin==2
if age<limit
x=true;
end
end
  3 comentarios
Muhammad
Muhammad el 23 de Jul. de 2022
In the statement above it's not asked for when x fails.That's why I never made statement when x fails. It simply shows nothing on command prompt when x fails.
Help me out and thanks for your response!
Muhammad
Muhammad el 23 de Jul. de 2022
function too_young = under_age(age,limit)
if nargin < 2
limit=21;
if age < limit
too_young=true;
else
too_young=false;
end
end
if nargin==2
if age<limit
too_young=true;
else
too_young=false;
end
end
Thanks a lot Mr.Walter Roberson

Iniciar sesión para comentar.


MURSHED SK
MURSHED SK el 13 de Oct. de 2022
Editada: MURSHED SK el 13 de Oct. de 2022
This might help:
function too_young = under_age(age, limit)
if nargin <2
limit =21;
end
if age<limit
too_young = true;
else
too_young = false;
end
% the shortest way
  1 comentario
DGM
DGM el 13 de Oct. de 2022
Again, how is this different from the many existing answers?
Also, this isn't the shortest way. John's answer at the top of the thread is shorter, and is thoroughly explained.

Iniciar sesión para comentar.


JASON
JASON el 4 de Dic. de 2023
function too_young=under_age(age,limit)
if nargin<2
limit = 21 ;
if age<limit
too_young=true;
else
too_young=false;
end
end
if nargin>1
if age < limit
too_young=true;
else
too_young=false;
end
end
% how about this ?
  2 comentarios
DGM
DGM el 4 de Dic. de 2023
This is the sixth duplicate of 367872. Trivial changes to variable names, spacing, or contextually-equivalent logical tests don't constitute new information.
Added to the notes I posted above. If I don't prune this sooner, it'll get pruned whenever I decide to clean up the thread -- whenever that might be.

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by