How to call functions from another m file
Show older comments
I have two scripts. In first script I have some functions.
script1.m:
function res = func1(a)
res = a * 5;
end
function res = func2(x)
res = x .^ 2;
end
In second script I call these functions. How to include script1.m in second script and call functions from script1.m?
Accepted Answer
More Answers (1)
Mahmoud Khaled
on 28 Mar 2018
Edited: Mahmoud Khaled
on 27 Jul 2020
You can add them to a MATLAB class. Then instantiate an object of this class and call any of the functions.
It should be something like this:
In a separate file (ex, functionsContainer.m)
classdef functionsContainer
methods
function res = func1(obj,a)
res = a * 5;
end
function res = func2(obj,x)
res = x .^ 2;
end
end
end
Then, in your script create an object:
myObj = functionsContainer;
Finally, call whatever function you like:
res1 = myObj.func1(a);
res2 = myObj.func2(x);
6 Comments
riki ragùa
on 25 Apr 2018
can you explaine more or give us example please ?
Mahmoud Khaled
on 27 Jul 2020
@riki: i upadated my answer.
Steven Lord
on 27 Jul 2020
If you wanted to do this I'd make those functions Static, since they don't need or use any state from the object itself.
classdef functionsContainer
methods (Static)
function res = func1(a)
res = a * 5;
end
function res = func2(x)
res = x .^ 2;
end
end
end
Use:
y = functionsContainer.func1(2) % 10
Another way to make local functions available outside their file is to have the main function return function handles to those local functions.
function [fh1, fh2] = example328959
fh1 = @func1;
fh2 = @func2;
end
function y = func1(a)
y = 5*a;
end
function z = func2(b)
z = b.^2;
end
Use as:
[f1, f2] = example328959;
f1(2) % also 10
Scott Shelton
on 15 Nov 2022
Edited: Scott Shelton
on 15 Nov 2022
Is there a way for example328959 to be inputed from a string?
I have a variable that stores example328959 as "example328959" as I need to be able to change the file that is referenced. Is there someway to reference this string as the file name in my "Use as:" code?
Stephen23
on 15 Nov 2022
Tomas
on 5 Aug 2024
if you define the methods as static, you dont even have to instantiate the class
E.g:
classdef Functions
methods(Static)
function y = func1(x)
% body
end
function y = func2(x)
% body
end
end
end
And then you can run from another script or cmd:
output = Functions.func1(input)
Categories
Find more on Functions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!