How to require a custom class type with addRequired?

조회 수: 4 (최근 30일)
Dominik Mattioli
Dominik Mattioli 2019년 12월 5일
댓글: Dominik Mattioli 2019년 12월 5일
I have a custom class,
classdef foo
properties
%Property stuff
prop1;
end
methods
function obj = foo( )
%Constructor stuff.
obj.prop1 = 'test';
end
end
end
and I want the input of a function to require that the variable type is this custom class.
function out = fun( varargin )
p = inputParser;
addRequired( p, 'InputName', @(x) isa( x, 'foo' ) );
parse( p, varargin{:} );
% Function stuff
end
When I try doing this
% Script.
objInstance = foo();
out = fun( 'InputName', objInstance )
I get this error:
" The value of 'InputName' is invalid. It must satisfy the function: @(x)isa(x,'foo'). "

채택된 답변

Steven Lord
Steven Lord 2019년 12월 5일
You probably want to use addParameter instead of addRequired.
If you're using release R2019b or later, consider using function argument validation instead of inputParser.
But if this function requires an input of this class, should it be a separate function or should it be a method defined inside the class itself?
classdef foo
methods
function out = fun(x)
% x MUST be a foo (which could mean it's a subclass of foo)
end
end
end
  댓글 수: 1
Dominik Mattioli
Dominik Mattioli 2019년 12월 5일
It took me a while but I finally understand why you suggested using addParameter instead. This is a great answer to a question that I now see is a little naive, thank you.

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

추가 답변 (1개)

Luna
Luna 2019년 12월 5일
Variable out is not defined in the function bar. Also bar is already a built-in function. Use another function name instead.
  댓글 수: 1
Dominik Mattioli
Dominik Mattioli 2019년 12월 5일
I'll edit the question to have my original class and function names. I changed them to be easier to read for this question.

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

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by