MATLAB: Object property as function argument

functionobjectoopproperty

Hey all, I want one of the functions in my class to contain an input parameter which is a property of an object of that class.
For example:
classdef MyClass
properties
myproperty = cell(8)
end
methods
x = myfunction1 (mycellarray)
end
myfunction2 (myobject)
y = myfunction1(myobject.myproperty)
end
end
end
However, I get the error
Undefined function 'myfunction1' for input arguments of type 'cell'.
It's nothing to do with cells in particular: if I try to pass a string, to myfunction3, which takes strings as an input, I get
Undefined function 'myfunction3' for input arguments of type 'char'.
Please help!

Best Answer

Methods of an object can only be called if at least one of the inputs is an instance of the object, or the method is a static method. Let's take a look at the method that you're trying to call (with the signature corrected.)
function y = myfunction2 (myobject)
y = myfunction1(myobject.myproperty)
end
Since this method only accepts one input, myobject, and is not static the only way that it can be called is if myobject isa MyClass. You're calling myfunction1 with whatever the myproperty property of the MyClass object contains; in this case, that would be a cell array. Since you're not calling myfunction1 with an object that isa MyClass, you can't call the method.
There are a couple potential solutions:
  1. Call myfunction1 with the myobject object and let myfunction1 extract the property value from the object itself.
  2. Make myfunction1 a class-related function in the MyClass class file rather than a method. Note that it would not be visible/accessible outside the class if you did this.
  3. If myfunction1 can operate without an instance of the class, you could make it a static method.