MATLAB: Script with all my functions -
maybe it's basic question here go. have .m functions accessed other scripts , functions.
i tried doing script functions , call in other functions code.
and got , error. please explain me how can solve this?
i'm trying this, gives me no error, , want do, still, way it? suggestions?
function pruebasllamafuncion funcionfem=@pruebastodasfunciones; a=funcionfem('overpower',1,5) b=funcionfem('poweroverwelming',2) end ... function a=f(nombre,varargin) f=str2func(nombre) a=f(varargin{1:end}); end function d=overpower(j,c) d=j*c; end function e=poweroverwelming(j) e=j; end
function placement
matlab, unlike number of other languages, permits single file contain 1 main function visible rest of system. main function first function. (documentation)
any functions defined after main function body called local functions. these functions each create own separate workspace (scope) , can called 1 and, of course, main function.
any functions defined within main function body called nested functions. these functions have own workspace able access , change variables of parent function under conditions. nested functions @ same nesting level can call each other , local functions, local functions cannot call nested functions since out of scope.
workarounds
there several options available depending on how proceed. @ risk of giving many options desiring exhaustive, i'll put list first last. things, recommend 1 or 2. other options more creating libraries/apis, included them show can done.
define function1 , function2 in separate m-files on matlab path or in present working directory call them normally.
wrap main body of work (the 1 calling functions) in function , define other functions local functions or nested functions. example:
function output = main(a,b,c) result=function1(a,b,c); result2=function2(b,d); ... % can define function1 , function2 here nested functions end % or can define function1 , function2 here local functions
- you can bit more fancy , have function returns function handles (pointers) local or nested functions , use (in example) struct call functions in script:
function functions = getfunctions() functions.f1 = @(a,b,c) function1(a,b,c); functions.f2 = @(a,b) function2(a,b); % can define function1 , function2 here nested functions end % or can define function1 , function2 here local functions
- if have r2013b or above, can same thing above using localfunctions function create cell array of handles local functions (in case, definitions required outside main function body).
function functions = getfunctions() functions = localfunctions(); % r2013b+ end % define function1 , function2 here local functions
- you can create class static functions:
classdef functions methods(static) % define function1 , function2 here , call them struct above. end end
i hope makes sense , helps.
Comments
Post a Comment