How to call a method from a class called A within another method from A?

233 ビュー (過去 30 日間)
Will
Will 2018 年 4 月 17 日
回答済み: Will 2018 年 4 月 17 日
Hello,
As the question suggests I want to call a method from a class lets call it class A with another a method of the same class. For example:
classdef A <handle
properties
eg_var
end
method
function multi_egvar(obj,n)
obj.eg_var = obj.eg_var*n;
end
end
end
The code above creates a class with a simple function that alters the variable eg_var by multiplying it by the input n. Now I want to create another function within the methods of the class, lets call it multi_n_3, which multiples eg_var by n three times. So if eg_var is 3 and n is 2, I want eg_var to become 3*2*2*2 which is 24. I want to ask if its possible to achieve this by calling the function multi_egvar three times within multi_n_3.
Also, I know I can achieve the same result just by writing a similar function with multiplying by n^3, but my goal here is to call the another function of the same class within another function of the same class.
Thank you in advance for your time and any help is welcomed.

回答 (2 件)

Robert U
Robert U 2018 年 4 月 17 日

Hi Will,

the following works:

classdef A <handle
  properties
      eg_var
  end
    methods
        function multi_egvar(obj,n)
              obj.eg_var = obj.eg_var*n;
        end
        function multi_n_3(obj,n)
            for ik = 1:3
                obj.multi_egvar(n);
            end
        end
    end
 end

Test the following:

 Test = A
 Test.eg_var = 3
 Test.multi_n_3(2)
 Test

Calling another method within one class is no problem. But you should think about tracking changes within your properties using set and get functions in order to not produce unwanted changes (as in that particular example property "eg_var" changes silently from 3 to 24). As a matter of fact calling the function 3 times in a loop is not efficient and should be solved differently.

Kind regards,

Robert


Will
Will 2018 年 4 月 17 日
Hi Robert,
Thank you for your reply and input. The solution you proposed worked successfully. I'm actually working on something else and came across this problem of wanting to to call another function within the same class. I thought posting all my codes here might take up too much of other's time to read so I just came up with this simple example on the fly since it can help me verify if what I want to do is possible.
Again, thank you for helping me verify that this, indeed, is possible.
Regards, Will

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by