- Call myfunction1 with the myobject object and let myfunction1 extract the property value from the object itself.
- 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.
- If myfunction1 can operate without an instance of the class, you could make it a static method.
Object property as function argument
13 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Steven Lord
2017-6-12
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:
0 个评论
更多回答(1 个)
Vandana Rajan
2017-6-12
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!