how do I call a member function in another member function in the same class in matlab ??

31 ビュー (過去 30 日間)
Derrick Gao
Derrick Gao 2018 年 8 月 14 日
コメント済み: Steven Lord 2022 年 10 月 19 日
these two functions are both in the same methods of a class. Thank you so much!!!
  1 件のコメント
Rik
Rik 2018 年 8 月 14 日
This looks very connected to your previous question.
I have hardly ever worked with classes, but aren't methods treating each other as local functions? That would mean you can just call it.

サインインしてコメントする。

回答 (1 件)

Eric
Eric 2018 年 8 月 28 日
There are two ways to call another method function from the same class.
First, you can use a dot/period to access the method from the class variable. Second, you can simply call the function and pass the class object as an argument.
Using MATLAB's Create a Simple Class Example as a basis, I've added the doBoth function below to illustrate both of these options.
classdef BasicClass
properties
Value
end
methods
function r = roundOff(obj)
r = round([obj.Value],2);
end
function r = multiplyBy(obj,n)
r = [obj.Value] * n;
end
function d = doBoth(obj,k)
d = [obj.multiplyBy(k), roundOff(obj)];
end
end
end
  2 件のコメント
Martin Zach
Martin Zach 2022 年 10 月 19 日
編集済み: Martin Zach 2022 年 10 月 19 日
Hi,
try "BasicClass.multiplyBy(k)" instead of "obj.multiplyBy(k)"->
if there is not instance yet, you have to make the methods Static
classdef BasicClass
properties
Value
end
methods (Static)
function r = roundOff(obj)
r = round([obj.Value],2);
end
function r = multiplyBy(obj,n)
r = [obj.Value] * n;
end
function d = doBoth(obj,k)
d = [BasicClass.multiplyBy(k), BasicClass.roundOff(obj)];
end
end
end
Steven Lord
Steven Lord 2022 年 10 月 19 日
That won't work in this scenario because both multiplyBy and roundOff need information from a specific instance. Static methods need to be able to be called without any instances of the class as inputs.
If I had an instance of the Human class, I could have a Static method named isMammal(). I don't need to know if there's a specific human we're discussing to know that whover it is, isMammal() must return true. But an isAdult() method could not be Static. The instance of Human representing me would return true for that method while ones representing a baby would return false.
Generally speaking, if your method must access any of the non-Constant properties of the class in which it is defined (or in a superclass) then conceptually it is not elgible to be Static.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by