Looped function with variables that update - possible?

2 Ansichten (letzte 30 Tage)
JD
JD am 23 Apr. 2018
Bearbeitet: Stephen23 am 23 Apr. 2018
Hi there,
I have a fairly complicated problem which if I was to describe in detail would be a bit of an information overload, so I'm gonna ask a simplified technical question, the answers to which I'll hopefully be able to apply to my problem as a whole.
I have a function that has the input variable h, and the output variable r:
function r = fun(h)
This function is then passed to the optimizer function fminsearch, which calculates a new value of h (the 'true' value) that minimizes r. I'm now trying to find a way to use this calculated 'true' value of h in the above function again, in a loop-like fashion, with each loop using the continuously updating 'true' value of h calculated in the function/fminsearch step immediately preceding it.
I've tried various things but to no avail, including playing around with global variables, although I'm not entirely sure how they work/ if they're suitable for this (I'm very much a Matlab novice!).
Hopefully that makes some sense, and any help is greatly appreciated.

Akzeptierte Antwort

Stephen23
Stephen23 am 23 Apr. 2018
Bearbeitet: Stephen23 am 23 Apr. 2018
What I understand is that you want to provide both current h value (as provided to the function by fminsearch while it is optimizing), and also the previously calculated value of h (the output from the last fminsearch call). This is easy by parameterizing the function, as explained in the MATLAB help:
You would need to define the function to accept both of these values, e.g.:
function r = fun(h,h_prev)
and then call it like this:
hp = 0; % initial value.
for k = 1:N
hp = fminsearch(@(h)fun(h,hp),[...]);
end

Weitere Antworten (1)

Star Strider
Star Strider am 23 Apr. 2018
I’m not certain what you’re doing, or what you want. The fminsearch function iterates internally to calculate the minimum of the function, and returns the argument (here ‘h’) that minimises it.
This example code uses the previous ‘h’ value to create a new initial parameter estimate in each iteration, storing the previous ‘h’ values:
fun = @(h) (h + 6).^2 .* (h - 12).^2 .* (h - 30).^2;
x0 = 1;
for k = 1:3
h(k) = fminsearch(fun, x0);
x0 = h(k) + 10;
end
x = -10:35;
plot(x, fun(x))
grid

Kategorien

Mehr zu Programming 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!

Translated by