Define a function in the main program

112 次查看(过去 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?

回答(2 个)

Walter Roberson
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
David C 2011-12-9
Walter, this is very useful information. Is this documented somewhere by Mathworks?
Thanks,
David
Jan
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
saurav shrivastava 2014-1-27
i want explanation of this code
  1 个评论
Walter Roberson
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 CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by