How to call functions from another m file

802 ビュー (過去 30 日間)
Sergey Zaitsev
Sergey Zaitsev 2017 年 3 月 9 日
コメント済み: DGM 2025 年 4 月 10 日
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.
  8 件のコメント
Koen
Koen 2025 年 4 月 10 日
編集済み: Koen 2025 年 4 月 10 日
Can you also put all these (I have quite a few functions) new functions into some folder; for example workspace/functions/myFunction.m?
And how would you call that?
EDIT: I found that you can call
addpath("functions");
myFunction();
In this case.
DGM
DGM 2025 年 4 月 10 日
You got it.
You can also edit the path using pathtool if you find it more convenient.

サインインしてコメントする。

その他の回答 (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 件のコメント
Stephen23
Stephen23 2022 年 11 月 15 日
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 Center および File ExchangeFunctions についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by