Passing parameters into .m function while trying to use fminsearch

4 views (last 30 days)
I have a "complex" function that is saved in a .m file that is then optimized with the fminsearch. The function requires some additional values that the only way I seem to be able to reference is to create global variables( which I prefer not to). I had tried to pass a struct in but it didn't seem to work. How can I pass parameters for a function being called on my fminsearch?
Here is the sample code Xstart = [286 340 5]; [finalValues,f,exitFlag] = fminsearch(@FcnGauss,Xstart);
%%
function f = FcnGauss(V)
global X1D Z1DROI
f = 0; X = X1D; Z = Z1DROI; h = V(1); mu = V(2); s = V(3);
idx = find(Z>0); for i = 1:length(idx) x = X(idx(i)); xbar = (x - mu)/s; del = Z(idx(i)) - h*exp(-xbar^2); f = f + del^2; end
end

Accepted Answer

Alan Weiss
Alan Weiss on 6 Aug 2018
You can pass extra parameters using nested functions or anonymous functions.
Alan Weiss
MATLAB mathematical toolbox documentation

More Answers (1)

Andreia Smith-Moritz
Andreia Smith-Moritz on 6 Aug 2018
Perfect! Thank you.I ended up using a nested function.

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!