Modify input command to automate it?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
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
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 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!