When calling this function how is the input error caught

1 次查看(过去 30 天)
This is a test function from the documentation. If I include a letter in the arguments instead of a number matlab reports an error. My question is how does matlab know its an error?
testValues(5,1,2,3,4,5,6,7,8,9,10,a)
function testValues(threshold,varargin)
minInputs = 2;
maxInputs = Inf;
narginchk(minInputs,maxInputs);
for k = 1:(nargin-1)
if (varargin{k} > threshold)
fprintf('Test value %d exceeds %d\n',k,threshold)
end %endif
end %endfor
end %end function
Thanks for any input, haha input get it!
D

采纳的回答

Mehmed Saad
Mehmed Saad 2020-4-18
编辑:Mehmed Saad 2020-4-18
since you include a letter a which Matlab think is a variable. so it try to pass the variable a to testValues but that variable doesnot exist so Matlab give you error
either you initialize the variable a
a =1;
testValues(5,1,2,3,4,5,6,7,8,9,10,a)
or you can use string to pass the letter
testValues(5,1,2,3,4,5,6,7,8,9,10,'a')
  2 个评论
Darnell Gawdin
Darnell Gawdin 2020-4-18
hahahahah, Doh!. Yes of course. Thanks! :) Sorry its been a long day.
Walter Roberson
Walter Roberson 2020-4-18
right. A letter would be a variable name or function name, and matlab would do name resolution. If it were a variable then the value of the variable would be passed down, and you would only be able to tell that apart from numeric constant by examining argname(). If it were a function name (not anonymous function as those are variables or expressions) then it would try to evaluate the function with no parameters and pass the first output into the testValues.
MATLAB would never look and say "Ah hah, you passed a name here instead of a numeric constant!". You can probe that with argname if you really want but argname cannot tell the difference between you passing in 10 and you passing in a+0 where a happens to contain 10: both show up with argname empty.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by