Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are forward declarations supported in MATLAB?

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?

like image 960
Peter Lustig Avatar asked Nov 11 '12 12:11

Peter Lustig


1 Answers

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.

like image 167
Eitan T Avatar answered Nov 08 '22 23:11

Eitan T