How to call multiple functions from a single .m matlab file

kumba picture kumba · Jul 3, 2013 · Viewed 11.8k times · Source

I have an algorithm written in one m file and i have several functions that i created in another .m file. I want to call these several functions i created in a separated file from the main algorithm .m file. I know how to call one function from a file to another, but here i want to be calling different functions i created in a separate file from my mail algorithm file. I have searched here, but the answers i got does not help and are not talking about what i want.

Here is a little illustration of what i am talking about:

main algo file
N = 30;
x = -10 + 20rand(1,N)
for j = 1 to N
  c = f1(x) % here i need to call different functions from another file
end

Functions with several variable- this is a separate file

Function perform

%% Function F1
f = f1(x)
 statements
end

%% Function F2
f = f2(x)
 statements
end

%% Function F3
f = f3(x)
 statements
end

%% Function F4
f = f4(x)
 statements
end

%% Function F5
f = f5(x)
 statements
end

end Perform

I want to be calling the F1 to F4 in the main algo .m file. How can you do this. Also it will be better if each time i run the main algo .m file, it prompts me to choose which of the F1 to F4 function i want to call and one i inputs and indicate the function in a dailog box, it calls that particular function. Any idea on how to do this please?

Answer

Eitan T picture Eitan T · Jul 3, 2013

The MATLAB documentation states:

MATLAB® program files can contain code for more than one function. The first function in the file (the main function) is visible to functions in other files, or you can call it from the command line. Additional functions within the file are called local functions. Local functions are only visible to other functions in the same file.

So in fact, the only function you can called outside this m-file is the first function (which is perform in your example), while the functions f1, ..., f5 can only be invoked inside the m-file, as they are local.

My suggestion is to stick with the recommended practice and define each function in its own m-file. However, if you don't want ending up with a multitude of m-files, and insist on having all functions implemented in the same m-file, you can work around this by passing additional arguments to the main function as follows:

function f = perform(func, x);
    switch(func)
        case 'f1'
            f = f1(x);
        case 'f2'
            f = f2(x);
        case 'f3'
            f = f3(x);
        case 'f4'
            f = f4(x);
        case 'f5'
            f = f5(x);
        otherwise
            error(['Unknown function ', func]);
    end

%// ... next follows the implementation of f1 through f5

and then invoke each of the functions f1, ..., f5 by calling perform with the appropriate function name string. For example:

perform('f1', some_variable)