Calling functions inside another function
12 次查看(过去 30 天)
显示 更早的评论
Hello, I have a problem with calling a function inside another function. I have a function PLearn that looks like this:
function LPar = PLearn(input,desOut,Par)
p = perc_learn(Par{1},input,desOut,Par{2},Par{3});
LPar = {p};
end
Then I have a function Err which gets in a parameter Name name of the function it should call (PLearn). This is the code for Err:
function E=Err(Name,NameL,Param,Tr,DTr,Ts,DTs)
%Lpar=PLearn(Tr,Dtr,Param);
Lpar=@Name(Tr,Dtr,Param);
dif=0;
for i = 1:size(Ts,2)
input=Ts(:,i);
%Out=@NameL(LPar,input);
Out=PRecall(Lpar,input);
dif=dif+abs(DTs(i)-Out);
end
% To make sure that err is a value between 0 and 1
% I will divide the number of miscalculated vectors by the total number of input vectors.
E=double(dif/size(Ts,2));
end
I call Err with these parameters:
Err(PLearn,PRecall,p,In,InO,TIn,TInO).
Now Err calls PLearn by passing pararametrs p,In and InO into it. It gives me this error:
In D:/FreematWorkspace/k-fold/PLearn.m(PLearn) at line 2
Error: Undefined function or variable Par
But if I run PLearn straight (by typing PLearn(In,InO,P)) with the same parameters it calculates the result no problem. So I don't get why it doesn't work through Err. I thought the problem might be with the use of name and calling the function through @ but even if I just call PLearn straight up from Err (the commented version) it still gives me the same error. I would appreciate any help on how to fix this.
Thank you so much
0 个评论
回答(1 个)
Steven Lord
2017-11-13
Lpar=@Name(Tr,Dtr,Param);
That's not the right way to define an anonymous function.
Err(PLearn,PRecall,p,In,InO,TIn,TInO).
This will try to call PLearn with 0 input arguments and pass the output from that call into Err. [Actually, it probably should throw an error about the trailing period first.]
If you want to "pass one function into another", don't pass the name of the first function into the second. Instead pass a function handle to the first function into the second. [That function handle could be an anonymous function.]
Your call would become:
Err(@PLearn, @PRecall, p, In, InO, TIn, TInO)
To evaluate that function handle inside Err:
function E=Err(fun,funL,Param,Tr,DTr,Ts,DTs)
value = fun(Tr, DTr, Param);
% etc
Search the documentation for the terms "anonymous function" and "function handle" for more information.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!