11.4: Subfunctions

Matlab and Octave Programming for STEM Applications · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    11.4: Subfunctions

      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 11.4: Subfunctions was last modified on Mon, 26 Jun 2023 04:18:34 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Carey Smith.