Calculating with Methods from Classes
11 views (last 30 days)
Show older comments
Hi,
I'm currently getting into classes and methods, due to a project I'm working on. I have a function which needs a whole lot of other funcions to calculate it's variables.
Until now i made a Class containing all the functions I need. Now I want to give the Class the needed Properties and want it to automatically run every function in the Class and print out the final result.
I have quite a hard time finding a solution for that because I don't really now how/where to start. To begin with, I don't even know if classes are able to do what I want.
Has anybody some advice? It would be greatly appreciated!
Greetings,
Leon
Answers (2)
Peng Li
on 31 Mar 2020
You have too many class methods that are not really methods specific for the class, as they never accept your object handle as an input. If they are necessary helper functions, make then out of the class def block. If they are necessarily need to be class methods, you'd better make the handle as the input, and within the function block, call explicitely the properties.
If you find it too difficult to organize so many properties (at least I do), you could probably categorize them into different groups by using struct. Your property names are too difficult to remember anyway.
Steven Lord
on 31 Mar 2020
Edited: Steven Lord
on 31 Mar 2020
To me, it seems like most if not all of these "calc<something>" methods should probably be property get methods and the properties those methods calculate should be Dependent properties. See the "Calculate Data on Demand" link in the description of the Dependent attribute on that page for more information.
But this assumes that you actually need to use a class. You don't really seem to have any methods that do something other than calculating a value. To me that suggests that a plain old function (perhaps one that operates on a struct array, to avoid requiring passing in fifteen input arguments in a specific order) would be better suited.
function HC = holstropCharacteristics(Geschwindigkeit, Deplacement, HolstropProperties)
% Define constants
g = 9.81;
vis = 1.1392e-06;
% % Unpack the properties if you want
Lwl = HolstropProperties.Lwl;
V = = HolstropProperties.V;
% and calculate with the unpacked properties
HC.Fn = calcFn(Lwl, V, g);
% Or pass the properties into the subfunctions en masse
% and let the subfunction retrieve what they need or want
HC.Rn = calcRn(HolstropProperties, vis);
% etc.
end
function Fn = calcFn(Lwl, V, g)
Fn = V/(sqrt(Lwl*g));
end
function Rn = calcRn(HP, vis)
Rn = (HP.V*HP.Lwl)/vis;
end
See Also
Categories
Find more on Characters and Strings 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!