Search code examples
matlabcalling-convention

How to set function arguments to execute different set of m-files?


I am using Matlab.

I have a main function main.m. And I have two sets of m-files, named:

Set A = {Area_triangle.m, Perimeter_triangle.m}
Set B = {Area_square.m, Perimeter_square.m}

Is there any methods such that it can achieve main(triangle) can execute m-files in set A while main(square) can execute m-files in set B?

Thanks in advance


Solution

  • To run a Matlab-script stored in an m-file, you can use run. With a switch-statement, it's easy to determine which set should be used. Then we can iterate over all the files in the given set and execute the scripts.

    The following function can be called with main('triangle') and main('square'):

    function main(shape)
    
    A = {'Area_triangle.m', 'Perimeter_triangle.m'};
    B = {'Area_square.m', 'Perimeter_square.m'};
    
    switch shape
        case 'triangle'
            S = A;
        case 'square'
            S = B;
        otherwise
            error('Shape not defined!');
    end
    
    for i = 1:length(S)
        run(S{i})
    end