How to call function from one function .m file to another function .m file?
170 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Star Strider
am 12 Jul. 2022
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.
Antworten (1)
Steven Lord
am 12 Jul. 2022
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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!