10.1.3: Subfunctions
- Page ID
- 95598
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:
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.