MATLAB: How to get implicit conversion between strings and function handles when using in-line property validation in a MATLAB class

MATLABmethodsooppropertysetsettervalidation

I have defined the MATLAB class 'simpleClass' as shown below:
classdef simpleClass
properties
prop1 function_handle
end
end
When I create an instance of this class and try to assign a 'char' to 'prop1', as shown below, an error is thrown despite the fact that strings that are function names are convertible to function handles.
>> a = simpleClass
>> a.prop1 = 'sin'
Error setting property 'prop1' of class 'exampleClass':
Invalid data type. Value must be function_handle or be convertible to function_handle.
However, the conversion below returns a valid function handle:
>> str2func('sin')
ans =
function_handle with value:
@sin
Why is an error thrown when I try to set 'prop1' using a string?

Best Answer

Unfortunately, implicit conversion between 'char' arrays and function handles is not currently supported for inline property validation.
As a workaround, you can declare a setter method for 'prop1' that explicitly performs the type checking and conversion desired. The example below illustrates how to do this:
classdef simpleClass
properties
prop1
end
methods
function obj = set.prop1(obj,arg)
if ischar(arg)
obj.prop1 = str2func(arg);
elseif isa(arg,'function_handle')
obj.prop1 = arg;
else
error('Unaccepted datatype')
end
end
end
end