How to call a function from outside itself ?

조회 수: 19 (최근 30일)
DIMITRIOS THEODOROPOULOS
DIMITRIOS THEODOROPOULOS 2019년 1월 23일
댓글: DIMITRIOS THEODOROPOULOS 2019년 1월 23일
Altought it is basic i cannot understand how it works in Matlab 2017..
I have 2 simple functions
function y1=square(x1)
y1=x1^2;
end
function y2=cube(x2)
y2=x2^3;
end
i can call square function but i cannot call cube...
>> square(5)
ans =
25
>> cube(5)
Undefined function or variable 'cube'.
why does this happen?
I cannot also use global, persistent to help with this...

채택된 답변

Stephen23
Stephen23 2019년 1월 23일
편집: Stephen23 2019년 1월 23일
"why does this happen?"
Because local functions are only callable within the same file. This is explained in the documentation: "In a function file, the first function in the file is called the main function. This function is visible to functions in other files, or you can call it from the command line. Additional functions within the file are called local functions, and they can occur in any order after the main function. Local functions are only visible to other functions in the same file."
If you want to call both functions outside of that file then by far the easiest way to achieve that is to write each function in its own file. If you really really need to call a local function outside of its own file then create a handle to it and pass that handle as an output argument (I have only rarely seen use cases where this is required).
  댓글 수: 7
Stephen23
Stephen23 2019년 1월 23일
"And yes i use google but i need a more ''professional'' opinion!!"
The "professional" opinion is that you should avoid using global variables:
The MATLAB documentation states "Use global variables sparingly, if at all":
DIMITRIOS THEODOROPOULOS
DIMITRIOS THEODOROPOULOS 2019년 1월 23일
thank you very much!!

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by