How to test for errors on a function inputArgs

조회 수: 15 (최근 30일)
Barak Garty
Barak Garty 2022년 11월 2일
답변: Walter Roberson 2022년 11월 2일
I wrote the following function:
function feet2metersV2(altitudeValue)
%feet2meters converts feet to killometers and meters
% Version 2.0
if (length(altitudeValue)>1 || altitudeValue<0) %tests for user entering proper input
fprintf('You entered more than single input as altitude value or a non-positive value. \n')
else
% rest of my code
end % if block end
end % function end
If user call that function like this: feet2metersV2(3 4) or feet2metersV2() than MATLAB throws a build-in error.
I like to code a try-catch block for it in the function code. How do I address it? since it happens befor the code even starts. I am using a 2019a MATLAB version so I dont have the new 'argument validation' option.
Many thanks in advence.

답변 (1개)

Walter Roberson
Walter Roberson 2022년 11월 2일
For the case of being called with no parmeters or too few parameters, you can use nargin() to test how many parameters were provided, and can do whatever is appropriate for the situation.
For the case of being called with too many parameters, then nargin() alone cannot solve the problem: MATLAB would normally detect the problem before entering the function at all. However, if you specify the last parameter name as the magic name varargin then MATLAB will permit any number of parameters, and you can then test nargin() to determine if too many parameters were passed. For example,
function feet2metersV2(altitudeValue, varargin)
if nargin < 1
%no parameters case
elseif nargin > 1
%too many parameters case
else
%right number of parameters case
end
end

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by