How to use nested functions to build a code that compares inputs
이전 댓글 표시
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
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
2020년 10월 6일
Gin
2020년 10월 6일
채택된 답변
추가 답변 (1개)
Rasheed Aiyedun
2022년 8월 30일
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
카테고리
도움말 센터 및 File Exchange에서 Debugging and Improving Code에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!