Problems creating function handle to method from user input text string during object construction

1 visualización (últimos 30 días)
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
end
end
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?

Respuesta aceptada

Oleg Komarov
Oleg Komarov el 7 de Sept. de 2012
function classify(obj)
% Should execute learner method specified by text string
obj.learner
end
Should be
function classify(obj)
% Should execute learner method specified by text string
obj.learner(obj)
end
because you're passing an argument to the function handle contained in learner.

Más respuestas (1)

Matt J
Matt J el 30 de Sept. de 2012
Note also that there is no reason to convert user_option to a function handle. You could have done this:
function obj = ssl(user_option)
if ismember(user_option,obj.valid_selection)
obj.learner = user_option;
else
error('Invalid Selection')
end
end
function classify(obj)
% Should execute learner method specified by text string
obj.(obj.learner);
end

Categorías

Más información sobre Language Support en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by