'Dynamically addressing MATLAB modules without using eval/feval

Consider a codebase with this file structure:

myScript.m (Script)
+modA/ 
    fn.m (Function)
+modB/ 
    fn.m (Function)

myScript.m must choose which of modA.fn or modB.fn to call at runtime using the outcome of a string str_moduleName.

Is there a way to avoid calling feval([str_moduleName,'.fn']) ?



Solution 1:[1]

I haven't tried this, but I guess you could build a struct with function handles:

S.modA = @modA.fn
S.modB = @modB.fn

Then you can call the function using the value of str_moduleName as follows:

S.(str_moduleName)()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cris Luengo