How to require a custom class type with addRequired?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Dominik Mattioli
am 5 Dez. 2019
Kommentiert: Dominik Mattioli
am 5 Dez. 2019
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'). "
0 Kommentare
Akzeptierte Antwort
Steven Lord
am 5 Dez. 2019
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
Weitere Antworten (1)
Luna
am 5 Dez. 2019
Variable out is not defined in the function bar. Also bar is already a built-in function. Use another function name instead.
Siehe auch
Kategorien
Mehr zu Argument Definitions finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!