Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Functions can be called within a function. As crazy as this sounds, this sometimes makes very complex code appear much more manageable by sectionalizing the code. To explain how to create a subfunction, let's look to the matlab help for an example:

function avg, med = newstats(u) % Primary function
% NEWSTATS Find mean and median with internal functions.
n = length(u);
avg = mean(u, n);
end

function a = mean(v, n) % Subfunction
% Calculate average.
a = sum(v)/n;
end Image Added

In the above example, there are two functions: the main function is called "newsstats". Within this function, there is a subfunction called "mean". The subfunction is defined the exact same way as the main function; but the difference is the subfunction can only used when the main function is used - you can not call your subfunctions in the command window.

...