How to call function from one function .m file to another function .m file?

조회 수: 178 (최근 30일)
Oliver Edy
Oliver Edy 2022년 7월 12일
답변: Steven Lord 2022년 7월 12일
I have three scripts: main.m, and two functions function1.m and function2.m in a subdirectory called +functions.
Currently, I call function1.m from main.m, like follows:
function1.m
function y = function1(x)
y = x + 1;
end
script.m
import functions.function1
x = 1
y = function1(x)
z = y * 2
However, I want to call function1.m in function2.m, and then call function2.m in main.m, a bit like this:
function2.m
function z = function2(x)
y = function1(x)
z = y * 2;
end
script.m
import functions.function1
import functions.function2
z = function2(x)
Is it possible to call one function in another like this? Or would I have to have function1 and function2 in the same .m file?
  댓글 수: 3
Star Strider
Star Strider 2022년 7월 12일
Calling them the way you descirbed in:
function z = function2(x)
y = function1(x)
z = y * 2;
end
should work.
Nothing else should be required so long as they are all in your MATLAB search path. See: What Is the MATLAB Search Path? for details if you are not familiar with it.

댓글을 달려면 로그인하십시오.

답변 (1개)

Steven Lord
Steven Lord 2022년 7월 12일
The import function doesn't "globally import" so if your functions are in packages you need to either use the package name or import in each of the functions.
So if you want functions.function2 to be able to call functions.function1:
function z = function2(x)
y = functions.function1(x)
z = y * 2;
end
or
function z = function2(x)
import functions.function1;
y = function1(x)
z = y * 2;
end
To forestall what I expect is your next question no, there is no way to automatically make package functions treat other functions in the same package as imported by default. Doing so would require a new syntax for calling a function in the global namespace that shares the name of a function in the package.

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by