フィルターのクリア

Call a function inside a script from another script

124 ビュー (過去 30 日間)
Leonard
Leonard 2014 年 9 月 4 日
コメント済み: Geoff Hayes 2014 年 9 月 6 日
Hey people, I have a short question and couldn't find an answer to that:
I have a script with several functions and I want to call a particular function inside this script, but from another script.
If that sounds confusing here a quick example:
m-File "AllFunctions"
function a
a = 1;
function b
b = 1;
m-File "Main"
>>> Now I want to get access to function a from the "AllFunctions"-m-File.
Would be great if you can help me or if you recommend a better way handling such a problem.
Thanks!
Leo

採用された回答

Geoff Hayes
Geoff Hayes 2014 年 9 月 4 日
Leonard - I'm pretty sure that you can't do that. If your m-file is named AllFunctions.m, then either it is a script that you can run or it is a function which has the same name as the file which you can call (passing in arguments, getting a result, etc.), but you cannot access any other function that has been defined in that file.
If I wanted to do something like what you suggest, then I would create a class with static methods. I've done this for C++ when I wanted a class that had some common algorithms, so there is no reason why you can't do something similar in MATLAB. Suppose the following is your class definition (saved in a file called AllFunctions.m)
classdef AllFunctions
methods(Static)
function [x] = a
x = 1;
end
function [x] = b
x = 2;
end
function [x] = c(var)
x = 3*var;
end
end
end
There isn't all that much to it: the class definition with a section for static methods, in this case, for the functions a, b, and c. In the Command Window, I can invoke each function as
>> AllFunctions.a
ans =
1
>> AllFunctions.b
ans =
2
>> AllFunctions.c(27)
ans =
81
So using a class, you should be able to do something along the lines of what you want.
  3 件のコメント
Leonard
Leonard 2014 年 9 月 6 日
Implemented it today and it works awesome! Thank you so much! This is great :)
Geoff Hayes
Geoff Hayes 2014 年 9 月 6 日
Glad it worked out!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSoftware Development Tools についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by