Dynamically assign function to object method

1 回表示 (過去 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 Center および File ExchangeMultiobjective Optimization についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by