How to call functions from another m file

조회 수: 2,847 (최근 30일)
Sergey Zaitsev
Sergey Zaitsev 2017년 3월 9일
댓글: Tomas 2024년 8월 5일
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?

채택된 답변

Adam
Adam 2017년 3월 9일
You can't if the functions are defined as local functions in the script1 file.
Just put the functions in their own separate file (of the same name as the function and on your path) if they are being used by both script1 and script2.
  댓글 수: 6
Mathlabuser 29952
Mathlabuser 29952 2024년 7월 12일
Thanks! I'll try. The script can be saved as script.m as well and call the numtimes2.m?
DGM
DGM 2024년 7월 12일
Yes. A script can call its own local functions, or it can call a function file like numtimes2().

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Mahmoud Khaled
Mahmoud Khaled 2018년 3월 28일
편집: Mahmoud Khaled 2020년 7월 27일
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
Tomas
Tomas 2024년 8월 5일
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)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Functions에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by