Call a function inside a script from another script

60 次查看(过去 30 天)
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Manage Products 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by