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

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 commentaires

What is this supposed to achieve?:
import functions.function1
I don't see anything stopping you from calling function1 from function2, and function2 from your script (except for those strange IMPORT commands).
Are you runing python?
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.

Connectez-vous pour commenter.

Réponses (1)

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.

Catégories

Produits

Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by