Looped function with variables that update - possible?
Show older comments
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.
Accepted Answer
More Answers (1)
Star Strider
on 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
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!