Call a function inside a script from another script
조회 수: 135 (최근 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
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Software Development Tools에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!