|
"beda meda" <b.meda@centrum.cz> wrote in message
news:h1deiq$rsn$1@fred.mathworks.com...
> Hi,
> I have two m-files. One is test.m and it contains this function:
> function x = test
>
> Another is target.m and it contains two functions:
> function result = target(a)
> function answer = start(b)
Since the name of the file is target.m I assume the target function is the
first one in the file and is therefore the primary function in that file,
with start being a subfunction.
http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f4-39629.html
http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f4-70666.html
> Both m-files are in one directory. Now I know that when I write in test.m
> function x = test
> given_result = target(param);
>
> it will launch whatever is in fuction target(a) which is in target.m. But
> how can I call from m-file test.m function start(b) in target.m? Something
> like this
>
> function x = test
> given_answer= start(param);
>
> but this will obviously not work.
As stated in the second of the pages I linked above:
"M-files can contain code for more than one function. Additional functions
within the file are called subfunctions, and these are only visible to the
primary function or to other subfunctions in the same file."
If you want to call the subfunction from outside its file, there are three
main options.
1) Move the subfunction to its own file as the primary function in that
file -- then it will be visible to other functions.
2) Call the primary function in the file and have it return a function
handle to the subfunction, as described in the third paragraph of the
reference page for function handles. Then call the subfunction using that
function handle.
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/function_handle.html
function fh = target
fh = @start;
3) Call the primary function in the file and have it call the subfunction
directly. This is often called a "switchyard", as it's often implemented
using SWITCH:
function output = target(functionToCall, varargin)
switch functionToCall
case 'start'
output = start(varargin{:});
otherwise
% Do other stuff
end
Alternately, instead of SWITCH, you can use FEVAL:
function output = target(functionToCall, varargin)
output = feval(functionToCall, varargin{:});
Personally I prefer option 1 in most cases, although I have used the other
two on occasion.
--
Steve Lord
slord@mathworks.com
|