Object property as function argument

24 views (last 30 days)
Joshua Diamond
Joshua Diamond on 10 Jun 2017
Answered: Steven Lord on 12 Jun 2017
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!

Accepted Answer

Steven Lord
Steven Lord on 12 Jun 2017
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.

More Answers (1)

Vandana Rajan
Vandana Rajan on 12 Jun 2017
Hi,
You may see the code below. This doesn't throw any error.
classdef MyClass
properties
myproperty = cell(8)
end
methods
function x = myfunction1 (myproperty1)
x = myproperty1;
end
function myfunction2 (obj)
y = myfunction1(obj.myproperty);
end
end
end

Community Treasure Hunt

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

Start Hunting!

Translated by