Info

This question is closed. Reopen it to edit or answer.

How can I define custom behaviors for objects of the same class (passing in a function)?

1 view (last 30 days)
Hi I'm trying to write a class which can take in custom defined behaviors. The only way I can think to do this is to define a function and pass it into a class. Is this the correct way to do it?
temp = cvcustom([],@indices);
function ind = indices(arr)
ind = ~arr;
end
In a separate file:
classdef cvcustom
...
function cvc = cvcustom(labelMatrix,trainFun,testFun)
cvc.training = trainFun;
end
...
end
  1 Comment
Adam
Adam on 5 Aug 2014
Edited: Adam on 5 Aug 2014
Passing a function handle into a class function is a method I have used a few times in order to inject specialised behaviour to a generic class so it should work fine. The only difficulty tends to come with parameterising the function handle as obviously if it has variable arguments these have to be passed in within the function of the class itself.
If I understand correctly your function being passed in takes an argument so you cannot just pass in '@indices'. Is that argument something that is fixed before being passed to the class or is it something the class must fill in?
If the latter you would need something like:
f = @(x) indices(x)
temp = cvcustom( [], f )
then in your class function:
cvc.training = trainFun( yourInputArgument );
where 'yourInputArgument' would be something supplied by the class that the function is expecting.
The other option I use more regularly is to pass in an object of another class to provide the custom defined behaviour.
e.g. I may have a base class with e.g. an abstract 'calculate' function, then derived classes which provide their own implementations of 'calculate'. You can then pass in an object of one of the derived classes and call the 'calculate' function on it within your class function.
In Matlab the common base class isn't strictly necessary as polymorphism isn't really a part of the language, you can pass in any class that happens to have a 'calculate' function, irrespective of whether they are of a specific hierarchy, but I prefer the base class approach because it helps me validate the argument passed in as being of base-class type (or any of its derived classes). Then I know that when I call calculate it will at least be on some expected class object.

Answers (0)

Community Treasure Hunt

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

Start Hunting!