What is an efficient way to use a sum of objective functions for fmincon?
2 views (last 30 days)
Show older comments
I'm preparing to use fmincon with an objective function that is a sum of (weighted) functions, such that the user of the program can select desired objective functions and specify the weight factors. The first idea that comes to mind is defining the objective function as a sum of functions defined in different .m files. This way, I can later on easily add objective functions by simply creating a new function. However, I am aware (rather, I strongly suspect) that it's costly to often call upon a function in another file.
My question is: is the approach that I sketch above reasonably efficient? If not, what other approach could I use which is both simple to use for me and efficient?
Other approaches that come to mind are
- writing all code in one function using if-statements, but that would not be so nice to use for me;
- using local/nested functions; not bad, but not as nice to use for me as having multiple functions in .m files.
0 Comments
Accepted Answer
Matt J
on 16 Aug 2021
Edited: Matt J
on 16 Aug 2021
However, I am aware (rather, I strongly suspect) that it's costly to often call upon a function in another file.
No, not really. If you are making calls repeatedly within a long for-loop, that might be the case, but here where the users are manually selecting a handful of desired functions, it presumably means the loop will be fairly short.
10 Comments
Walter Roberson
on 18 Aug 2021
When you have an end statement then a "static workspace" is geneated. Static workspaces have a "contract" that called functions cannot (are not permitted to) "poof" variables into existence -- so functions with static workspaces have more opportunities for optimization.
For example at the time that via_mfunc1 is being processed by itself, it does not know that via_mfunc2 will not assignin('caller') and mess something up in the workspace. Static workspaces say any called function will be blocked if it tries. Not just called functions: if a script is invoked in a static workspace, it is not permitted to create new variables.
... and when you can start relying on assignments you can see, and not having to worry about assignments you cannot see, then you can make tighter code that does not have to insert checks in case variables suddenly have new values or new datatypes.
So, on the whole, functions with static workspaces can be more efficient. But that might not show up for such simple functions as are being used in this test.
You might have noticed the functions in scripts have to have the matching end statements... which forces them to have static workspaces. Only functions with static workspaces can have nested functions and shared variables.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!