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

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