How to use nested functions to build a code that compares inputs
Mostrar comentarios más antiguos
I am somewhat of a newbie. I am writing a code that acts as an autograder with the following requirements. The function tests two functions (the student's solution and the instructor's reference solution) by calling them repeatedly with various input arguments and comparing the results. Both functions are assumed to take exactly one input argument. The inputs are two function handles followed by a variable number of additional input arguments. This grader function must call the two functions with each of the supplied input arguments one by one. If the results match all test cases, i.e. for each input argument, the grader function returns logical 'true'. Otherwise, it returns 'false'. Comparison must work for both arrays and scalars.
I have been working on the following code, which works for inputs like:
grader(@sin,@max,0)
grader(@sin,@max,0,1)
but not for inputs like:
grader(@cos,@cos,0,1,[-pi,0,pi])
Please help! Thank you.
function result = grader(a,b, varargin)
result = true;
in = varargin;
for ii = in{1}:in{end}
A = a(ii);
B = b(ii);
end
if isequal(A,B)
result = true;
else result = false;
end
end
3 comentarios
Although the title is "How to use nested functions to build a code that compares inputs", nothing in your question seems to be related to nested functions: https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html
Note that the colon operation here:
in{1}:in{end}
is very unlikely to be useful for you: in some cases you will get an error, in other cases you will get a vector of values which may or may not be provided as input values. In MATLAB it is usually best to iterate over indices, not data values.
Gin
el 6 de Oct. de 2020
Gin
el 6 de Oct. de 2020
Respuesta aceptada
Más respuestas (1)
Rasheed Aiyedun
el 30 de Ag. de 2022
function out = grader(a,b,varargin)
out = true
for ii = 1:length(varargin)
c = varargin{ii};
d = a(c);
e = b(c);
if d == e
out = true;
else
out = false
end
end
end
Categorías
Más información sobre Introduction to Installation and Licensing en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!