How do i call a function inside another function?

조회 수: 266 (최근 30일)
Mohammed
Mohammed 2016년 9월 3일
댓글: Jan 2018년 12월 18일
i wrote 2 functions separately. in one of these functions, i need to call the other function inside it? how do i do that? Thanks :)

답변 (2개)

KSSV
KSSV 2016년 9월 3일
I am giving an example here. The below first function calls a seconds function to calculate the sum of three numbers.
function K = firstfunction(a,b,c)
L = secondfunction(b,c) ;
K = a+L ;
This is the second function which calculates sum of two numbers.
function L = secondfunction(b,c)
L = b+c ;
Call the first function in Main file/ matlab work space:
s = firstfunction(1,2,3) ;
  댓글 수: 3
Stephen23
Stephen23 2018년 12월 18일
편집: Stephen23 2018년 12월 18일
"My question is will the variable L be local or global to the calling function?"
L is not declared as global. It exists
  1. in the workspace where it is defined, and
  2. where it is passed as an output argument.
What do you mean by "the calling function" ?
Jan
Jan 2018년 12월 18일
@Soumen Kuma Mondal: Try it. It is very cheap to run the shown code and to use the debugger to step throught the code line by line. Then you can see in the WorkspaceBrowser, which variables are existing.
You need the command global to make a variable global. Another method to share data is to created a nested function:
function K = firstfunction(a,b,c)
L = secondfunction(b,c) ;
K = a+L ;
function L = secondfunction(b,c)
L = b+c ;
disp(K)
end
end
Now secondFunction is visible inside the firstFunction only and e.g. K is existing inside secondFunction.

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


KSSV
KSSV 2016년 9월 3일
simple....write the function (output = functionname(inputs)) inside the function you want...
  댓글 수: 1
Mohammed
Mohammed 2016년 9월 3일
Thank you! i tried that but it does not work:( so i wrote the main function and then i called the other function inside it(in the same format you have specified). i think this is because the inputs of the function i called are not specified so MATLAB will not be able to run the code while it contains other unknowns from the previous function so i think i would have to enter the inputs of the other function i called but i do not know how to do that!

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

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by