필터 지우기
필터 지우기

Can I call a function defined within another function .m file?

조회 수: 24 (최근 30일)
Paul
Paul 2018년 6월 21일
답변: Guillaume 2018년 6월 21일
Hello. Consider a file titled giveA.mat :
function A = giveA(argA)
% Main function
b = giveB(argB);
...
end
function b = giveB(argB) % defined within one file
% simple sub-function
end
% End of file
I'd like to call giveB() somewhere else in the code, but it would be very convenient for me to keep this function as is.
Is there a syntax which will allow this, i.e. can I call giveB() from, say someOtherFunction(). I expect something like
b = givA(argA)/giveB(argB)
or
b = giveA(argA)>giveB(argB)
as this is how Matlab displays location of giveB() in error messages.

채택된 답변

Guillaume
Guillaume 2018년 6월 21일
As is, it is not possible. Local functions can only be accessed from within the files where they are defined.
The only way to export a local function is to pass a handle to it from the main function of the m file, so you would have to modify your giveA to return a handle to giveB, which would not be compatible with your desired syntax.
What you could do is to wrap both functions in a class:
classdef FunContainer
methods (static)
function A = giveA(argA)
%...
end
function B = giveB(argB)
%...
end
end
end
which you can use as
b = FunContainer.giveA(A) / FunContainer.giveB(B)

추가 답변 (2개)

Fangjun Jiang
Fangjun Jiang 2018년 6월 21일
No. It is a local function. If it needs to be used outside, it has to be saved in a separate .m file.

OCDER
OCDER 2018년 6월 21일
The next closest thing is to define an object class with static methods (give.m)
%give.m
classdef give
methods(Static)
function A = A(argA)
A = argA;
disp('I gave A');
end
function B = B(argB)
B = argB;
disp('I gave B');
end
end
end
To use "giveA", use "give.A" instead.
D = give.A(3)/give.B(10);

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by