Dynamically assign function to object method
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (0)
Siehe auch
Kategorien
Mehr zu Surrogate Optimization finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!