Looped function with variables that update - possible?
3 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Stephen23
2018-4-23
编辑:Stephen23
2018-4-23
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
0 个评论
更多回答(1 个)
Star Strider
2018-4-23
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
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!