Is it possible to use a function in a m-file, which is implemented in a later part of the same file: in similar style to other programming languages such as C?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Of course.
In such an m-file, the local functions would be declared after the main function. For example:
In this example
main_funccan invokehelper_func1andhelper_func2without any problems. You can test-run it and see for yourself:There is no need for any forward declaration.
By the way, a lot of m-files that come with MATLAB are implemented this way. For instance,
corrcoef. Withtype corrcoef, you can see that.Note: local function definitions are not permitted at the prompt or in scripts, so you have to have declare a “main” function in your m-file. As an exercise, copy-paste my example into a new m-file, remove the declaration of
main_func(only the first line) and see what happens.