Reputation: 8327
My Matlab script .m file is getting too big. I want to move functionality to multiple .m files my moving functions from the primary file to a several other .m files, each based on category of functionality.
How can the primary .m file 'call' functions in these other new .m files?
Upvotes: 9
Views: 43794
Reputation: 6424
All the information provided in my answer can be found in Function Basics at MATHWORKS.
How to make a function in MATLAB? You use the following template. In addition the name of the function and the name of the file should be similar.
% ------------------- newFunc.m--------------------
function [out1,out2] = newFunc(in1,in2)
out1 = in1 + in2;
out2 = in1 - in2;
end
%--------------------------------------------------
For using multiple functions you can apply them either in separate m-file
s or using nested/local
structures:
Separate m-files:
In this structure you put each function in a separate file and then you call them in the main file by their names:
%--------- main.m ----------------
% considering that you have written two functions calling `func1.m` and `func2.m`
[y1] = func1(x1,x2);
[y2] = func2(x1,y1);
% -------------------------------
local functions:
In this structure you have a single m-file and inside this file you can define multiple functions, such as:
% ------ main.m----------------
function [y]=main(x)
disp('call the local function');
y=local1(x)
end
function [y1]=local1(x1)
y1=x1*2;
end
%---------------------------------------
Nested functions:
In this structure functions can be contained in another function, such as:
%------------------ parent.m -------------------
function parent
disp('This is the parent function')
nestedfx
function nestedfx
disp('This is the nested function')
end
end
% -------------------------------------------
You cannot call nested function from outside of the m-files. To do so you have to use either separate m-files for each function, or using class structure.
Upvotes: 10