How to call a method from a class called A within another method from A?
Mostrar comentarios más antiguos
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.
Respuestas (2)
Robert U
el 17 de Abr. de 2018
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
endTest 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
el 17 de Abr. de 2018
1 voto
Categorías
Más información sobre Functions en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!