MATLAB Answers

How to do multiple functions or subroutines in one .m file

4 views (last 30 days)
Collin Greenwell
Collin Greenwell on 25 Aug 2021
Edited: Stephen on 25 Aug 2021
I am working on a project for a class and the professor is requiring that we use functions for evaluating certain things (using the bisection and secant method), but he also requires that we only turn in a single .m file. Normally I would create the functions in seperate files and then call them in the main code, but he does not want this. He insists there is a way to do multiple "subroutines" (his phrasing, although I havent heard of that and when I look it up it seems to be the same thing as a function. The main problem is if I try and put a function into my main project code named project1.m it says that the function (bisect) is not the same as the file name, which is why I've always done them seperately. I have looked throughout these forums and the methods I've seen dont seem to make much sense. Ill put a shortened version of my code, as the guts of it don't matter since they run fine. Overall i need a way to have two funcitons or "subroutines" in one .m file and be able to call them. The main problem is having them in the same file and using them all in the same script.
function [p,i] = bisect(f,a,b,tol,n0)
% code for evaluating the function
end
[p,i] = bisect(f,a,b,tol,n0);
disp(p);
disp(i);
  1 Comment
Stephen
Stephen on 25 Aug 2021
"He insists there is a way to do multiple "subroutines" (his phrasing, although I havent heard of that and when I look it up it seems to be the same thing as a function."
They are called local functions:
"The main problem is if I try and put a function into my main project code named project1.m it says that the function (bisect) is not the same as the file name, which is why I've always done them seperately."
If you are defining functions in a script then all function definitions must occur after all script code.
This is explained in the MATLAB documentation:

Sign in to comment.

Answers (1)

David Goodmanson
David Goodmanson on 25 Aug 2021
Hi Collin
Here is a quick example. Functions must go at the very end of the script, and each function must have an 'end' statement at the end to delineate it from the next function.
r = 1;
s = 2;
u = 0:.01:6;
x = afun(r,u);
y = bfun(s,u);
figure(1)
plot(x,y)
grid on
function x = afun(r,u)
x = r*cos(u);
end
function y = bfun(s,u)
y = s*sin(u);
end

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by