Skip to main content
Engineering LibreTexts

10.1.3: Subfunctions

  • Page ID
    95598
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

      There is an option in MATLAB to put a function at the bottom of a script or function file. Such a function is called a subfunction. 

      Subfunctions are never necessary, but can be convenient if the function is a particular function for only 1 script. A general purpose user function should be put in its own file.

      In Octave, a subfunction can only be put in a function file, not in a script file.

      Consider the exercise from the previous section with the script fzero_y_fun1.m and the function y_fun1.m

      The function could be put at the bottom of the script shown in this example:

      Example \(\PageIndex{1}\) y_fun1 subfunction

      x = 1: 0.1 :6;
      % (1 pt) Evaluate the equation using your x vector
      y1 = y_fun1(x);

      %% C. (1 pt) Open figure and plot this function.
      % A plot of the function lets us estimate a root.
      figure(1)
      plot(x,y1)
      grid on;
      title('fzero1root\_fcnfile\_example.m CSmith')
      hold on;
      plot(x,zeros(size(x)),'r') % Plot a line for y = 0
      %% D. (4 pts) Use the fzero() function to find a root near x = 4
      x_solution = fzero(@y_fun1, 4)
      % x_solution = 3.5656

      %% E. fzero() can also be used to find a root between 2 values
      x_solution = fzero(@y_fun1, [3,5])

      %%
      function y1 = y_fun1(x)
      y1 = log(x)./x.^2 -0.1;
      end

      Solution

      Add example text here.

       

       


      This page titled 10.1.3: Subfunctions is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Carey Smith.

      • Was this article helpful?