Access to variables of function in which calling function is nested
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
harleykitten
am 4 Apr. 2016
Kommentiert: harleykitten
am 5 Apr. 2016
I have this function:
function[measure1,minNumSensors1,feasible] ...
= measureAlg1FUN(numOfSensorstoTurnOn,sigmav,sigma_theta,...
sigmax,Dthres,Pmax,sourcePos,FCPos,sensorPos)
which contains a call to fmincon:
[P,fval]=fmincon(@objfun,P0,[],[],[],[],lb,ub,@confun,options);
When calling measureAlg1FUN, I get an error that the variables within this function are not accessible. These are needed for example in the constraint function defined as:
function[c,ceq]=confun(P)
a1=evalin('base','RvAlg');
a2=evalin('base','sigmax');
a3=evalin('base','sigma_theta');
a4=evalin('base','R_thetaAlg');
a5=evalin('base','RxAlg');
a6=evalin('base','Dthres');
Dp=diag(sqrt(P)/a2);
c=a3^2-a4*Dp*(Dp*a5*Dp+a1)^(-1)*Dp*a4'-a6;
ceq=[];
end
You can see that I have input the required variables using evalin from the base workspace. Of course, these variables do not exist within the base workspace, but within the workspace of function measureAlg1FUN. Changing the evalin argument from 'base' to 'caller', with the intent of having it access the variables in the caller function measureAlg1FUN, does not work either. I think this is because the caller is actually fmincon.
What can I do? Any help would be appreciated!
0 Kommentare
Akzeptierte Antwort
Geoff Hayes
am 4 Apr. 2016
harleykitten - if you want your confun function to be able to access the local variables defined in measureAlg1FUN, then you should nest confun within it.
For example, in the measureAlg1FUN.m file you would do
function[measure1,minNumSensors1,feasible] ...
= measureAlg1FUN(numOfSensorstoTurnOn,sigmav,sigma_theta,...
sigmax,Dthres,Pmax,sourcePos,FCPos,sensorPos)
% do something
% call fmincon
[P,fval]=fmincon(@objfun,P0,[],[],[],[],lb,ub,@confun,options);
% nest confun
function[c,ceq]=confun(P)
Dp=diag(sqrt(P)/sigmax);
c=sigma_theta^2-R_thetaAlg*Dp*(Dp* RxAlg*Dp+RvAlg)^(-1)*Dp* R_thetaAlg'-Dthres;
ceq=[];
end
end
Try the above and see what happens!
Weitere Antworten (1)
Steven Lord
am 4 Apr. 2016
If you're not modifying those variables (and you shouldn't be, as it could confuse the solver) you should pass them into the constraint function as additional parameters. The documentation for FMINCON links to a page describing several techniques by which you can do this.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Whos finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!