I have a pattern recognition class which the user specifies a learner (and various other options) by entering a text string. During the constructor I validate the user selection is a valid option then try to make a function handle that sets the learner property equal to a function handle that points to the appropriate learner method. A stripped down version is show below:
classdef ssl < handle properties learner valid_selection = {'learner1', 'learner2'}; end methods function obj = ssl(user_option) if sum(strcmp(user_option,obj.valid_selection)) == 1 obj.learner = str2func(user_option); else error('Invalid Selection') end end function classify(obj) % Should execute learner method specified by text string
obj.learner end function learner1(obj) display('Learner 1 was run') end function learner2(obj) display('Learner 2 was run') end endend
To construct object the user should input : a = ssl('learner1')
Method "learner1" should run and display "Learner 1 was run" when they type : a.classify
I have tried a variety of syntax for the line in the constructor shown below, none produce the desired results.
obj.learner = str2func(user_option);obj.learner = ['@obj.' user_option];obj.learner = str2func(['obj.' user_option]);
I can accomplish functionality through a series of nested if of switch/case statements but it makes the code extremely messy. Any suggestions on how this can this be done?
Best Answer