Problems creating function handle to method from user input text string during object construction
조회 수: 1 (최근 30일)
이전 댓글 표시
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?
채택된 답변
Oleg Komarov
2012년 9월 7일
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.
추가 답변 (1개)
Matt J
2012년 9월 30일
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Language Support에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!