Dynamically assign function to object method

조회 수: 4 (최근 30일)
Michael Häußler
Michael Häußler 2017년 6월 1일
편집: Michael Häußler 2017년 6월 2일
I am trying to design an optimization object, where I can dynamically change the costfunction to minimize.
What I need is a good way to implement this behaviour in Matlab.
Here is my minimal working example, with what my testcase should be able to do:
clc, clear all, close all
obj = SetMethodClass();
obj.methodToEvaluate = 'cube';
twentyseven = obj.evalFcn(3)
obj.methodToEvaluate = 'square';
nine = obj.evalFcn(3)
Here is what my class implementation looks like:
classdef SetMethodClass < matlab.mixin.SetGet
properties
methodToEvaluate@char
end
properties (SetAccess = protected)
handleToEvaluationFcn@function_handle
end
methods
function set.methodToEvaluate(obj, method)
if ismember(method,{'square', 'cube'})
obj.methodToEvaluate = method;
%doesn't work (of course ;))
% obj.handleToEvaluationFcn = obj.(method);
%doesn't work
% obj.handleToEvaluationFcn = @obj.(method);
%doesn't work either ;)
% obj.handleToEvaluationFcn = str2func(['obj.' method]);
%now this does work, but it's ugly and I don't like switch case
switch lower(obj.methodToEvaluate)
case 'square', obj.handleToEvaluationFcn = @obj.square; %#ok
case 'cube', obj.handleToEvaluationFcn = @obj.cube; %#ok
otherwise, error('This method does not exist');
end
else
error([class(obj) ': %s is not a function to Evaluate'], method);
end
end
function y = evalFcn(obj,x)
y = obj.handleToEvaluationFcn(x);
end
end
methods(Access = private)
function y = square(~,x)
y = x^2;
end
function y = cube(~,x)
y = x^3;
end
end
end

답변 (0개)

카테고리

Help CenterFile Exchange에서 Direct Search에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by