Modify input command to automate it?

In older MATLAB, I was able to write a local input function so I could run code that tested another function that required input. Specifically, I had a subfunction like:
---
function out=input(a)
persistent incount;
if isempty(incount)
incount=1;
elseif incount==7
incount=1;
else
incount=incount+1;
end
if incount<7
out = 250+100*rand(1)
else
out=-1;
end
end
---
works like a dream in, say, 2014b. Seemingly doesn't work at all in 2017. Huge problem since I need my students to be able to run the code to check their work... Any ideas?

댓글 수: 4

Walter Roberson
Walter Roberson 2017년 10월 3일
To clarify: is it really a subfunction? As in you are adding the code to the end of the student's file so that it is visible within the file itself? And you are making the appropriate adjustment to the code to match "end" style (that is, in any one .m file, either no "function" statement should have a matching "end" statement, or else all of them must have.)
Or are you placing it onto the MATLAB path?
Image Analyst
Image Analyst 2017년 10월 3일
Why do you want to override a built-in MATLAB function with an unrelated one of your own? Why not choose a different name for your custom "input" function so there is no conflict?
OCDER
OCDER 2017년 10월 3일
How do you want to use input a? What is incount? Can you provide an example of a student code you want to test if it is correct via this subfunction?
Walter Roberson
Walter Roberson 2017년 10월 3일
편집: Walter Roberson 2017년 10월 3일
I understand the purpose of the code. The code is intended to substitute for student calls to input(), faking the result of typing for input() statements. The normal parameter to input() is a prompt, which the marker does not care about, so the parameter is ignored.
incount is counting the number of times that input() has been called this way, so as to be able to change the output. Probably the assignment requirements call for the program to terminate when a -1 is read in to the program. However, there is a bug in the program: it will never emit -1. Better would be something like,
function out = input(varargin)
need_str = false;
if nargin > 1 && ischar(varargin{2}) && strcmp(varargin{2}, 's')
need_str = true;
elseif nargin > 1 && ~verlessthan('matlab', '9.1') && isstring(varargin{2}) && varargin{2} == 's'
need_str = true;
elseif nargin > 1
error('Error using input(): second parameter is given but is not ''s''');
end
persistent incount;
if isempty(incount)
incount=1;
out = 250+100*rand(1);
elseif incount==7
incount=1;
out = -1;
else
incount=incount+1;
out = 250+100*rand(1);
end
if need_str
out = num2str(out);
end
end

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

제품

질문:

2017년 10월 3일

편집:

2017년 10월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by