Define a function in the main program
조회 수: 144 (최근 30일)
이전 댓글 표시
Hi, I coded my main program in Matlab and saved it as an M file.in the main program i call a function.where should i define this function? Can functions be defined in the man program? or they should seperately defined in an M file and just called in the main program?
댓글 수: 0
답변 (2개)
Walter Roberson
2011년 2월 28일
You can save them in separate .m files named according to the function, or you can write your code in one .m file using the structure
function main
....
end %notice this 'end' here
function firstfunction
...
end %notice this 'end' here
function secondfunction
...
end %notice this 'end' here
or you can write your code in one .m file using the structure
function main
...
function firstfunction %within the scope of main!
...
end %this 'end' is needed
function secondfunction %within the scope of main!
...
end %this 'end' is needed
...
end %this 'end' is needed
or you can write them in one .m file using the structure
function main
....
%no 'end'
function firstfunction
...
%no 'end' here either
function secondfunction
...
%no 'end' here either
The different choices have slightly different implications. Defining functions within the body of another function allows the subfunctions to share the variables of the containing function. The subfunction style can be mixed with the style that uses the explicit 'end' at the close of each routine. The subfunction style cannot be used in the style that leaves off the 'end' from the routines that share the same file. If you write several routines in the same file, then they either all must have 'end' or they must all not have 'end'.
You will not notice much difference between writing several routines in the same file with or without the explicit 'end', but if you use the 'end' then you cannot create new variables at run-time -- a limitation that allows more efficient code and better consistency checking.
Any routine saved in a separate file by itself can be called by another .m file, which is useful to build up a library of utility routines.
댓글 수: 2
David C
2011년 12월 9일
Walter, this is very useful information. Is this documented somewhere by Mathworks?
Thanks,
David
Jan
2011년 12월 9일
I'm sure it is documented. But I've searched for 10 minutes in the release notes, the local and the web docs - without success. Therefore I claim, that it is "not documented enough".
saurav shrivastava
2014년 1월 27일
i want explanation of this code
댓글 수: 1
Walter Roberson
2014년 1월 27일
You should start a new Question for that. You should also indicate your level of MATLAB experience so that people have an idea of how much detail to go into.
참고 항목
카테고리
Help Center 및 File Exchange에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!