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?
Of course.
In such an m-file, the local functions would be declared after the main function. For example:
function y = main_func(x)
% # This is the main function
y = helper_func1(x) .* helper_func2(x); % # Just an example
function h1 = helper_func1(x)
% # This is a helper function #1
h1 = x + 2; % # Just an example
function h2 = helper_func2(x)
% # This is a helper function #2
h2 = x * 2; % # Just an example
In this example main_func
can invoke helper_func1
and helper_func2
without any problems. You can test-run it and see for yourself:
>> main_func(8)
ans =
160
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. With type 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.
You can use the same m-file for implementation of many functions using a static class:
What was the original reason for MATLAB's one function = one file and why is it still so?