How do I call a user defined function in a method of a class?
4 views (last 30 days)
Show older comments
MathWorks Support Team
on 23 Aug 2017
Answered: MathWorks Support Team
on 24 Aug 2017
How do I call a user defined function in a method of a class?
I have properties and methods. I want to call a user defined function in the method similar to the way I call sin() function. How can I do that?
Accepted Answer
MathWorks Support Team
on 23 Aug 2017
Here is an example that demonstrates calling an user defined function in a method of a class.
This example uses two files, namely, the class definition file, "BasicClass.m", and the user defined function, "roundOffAndSquare.m". Please find these files attached.
The example class, "BasicClass" has a property, "Value", and a method, "multiplyBySquared(obj,n)" which calls an user defined function "roundOffAndSquare(val)". The class definition is as follows:
classdef BasicClass
properties
Value
end
methods
function r = multiplyBySquared(obj,n)
val = obj.Value;
squaredVal = roundOffAndSquare(val);
r = squaredVal * n;
end
end
end
The user defined function, "roundOffAndSquare(val)" is defined as follows:
function r = roundOffAndSquare(val)
r = round(val)^2;
end
This function rounds the input "val" to the to the nearest integer and returns the square of the rounded value. Please note that this will work as long as both the files are in the path!
In order to test the functionality, please execute the following commands in the command line:
>> a = BasicClass
>> a.Value = pi;
>> multiplyBySquared(a,3)
This command calls the method "multiplyBySquared", that in turn calls the user defined function, "roundOffAndSquare(val)" that is present in the path, and returns the answer as 27.
0 Comments
More Answers (0)
See Also
Categories
Find more on Construct and Work with Object Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!