# Using fminbnd within arrayfun to perform elementwise optimization with additional parameters (nested anonymous functions?)

2 views (last 30 days)
Adam Wasserman on 23 Sep 2020
Edited: Ameer Hamza on 23 Sep 2020
To optimize a scalar function with scalar inputs using fminbnd, you would call something like:
f = @(x) fun(x, a, b); % a and b are additional parameters
[xOpt, fOpt] = fminbnd(f, x1, x2); % x1 and x2 are the bounds
This works great in a scalar case, but now consider if the inputs x, a, and b are arrays X, A, and B. The desired behavior is to apply fminbnd elementwise with parameter arrays A, and B and bound arrays X1 and X2 and to create arrays Xopt and Fopt such that . I would like to do this using arrayfun (I know I could just loop over each element, but I really want to know how to do it this way for conciseness and just out of curiosity). The problem is that to use arrrayfun, the call to fminbnd must now also be packaged in an anonymous function. However, each elementwise array input in arrayfun must now also be passed downstream to fminbnd and then to fun. I imagine it would look something like this:
f = @(x, a, b) fun(x, a, b);
opt = @(a, b, x1, x2) fminbnd(f(x, a, b), x1, x2); % I don't even think you can pass arguments to f like this withing fminbnd
[Xopt, Fopt] = arrayfun(@(a, b, x1, x2) opt, A, B, X1, X2);
But this does not work, and Xopt and Fopt end up being a cell array of anonymous function if 'UniformOutput' is set to false, an error otherwise. How would I go about dealing with this nested series of anonymous functions?

Ameer Hamza on 23 Sep 2020
Edited: Ameer Hamza on 23 Sep 2020
This is the correct way to do such a thing
f = @(x, a, b) fun(x, a, b);
opt = @(a, b, x1, x2) fminbnd(@(x) f(x, a, b), x1, x2); % I don't even think you can pass arguments to f like this withing fminbnd
[Xopt, Fopt] = arrayfun(opt, A, B, X1, X2);
or
f = @(x, a, b) fun(x, a, b);
opt = @(a, b, x1, x2) fminbnd(@(x) f(x, a, b), x1, x2); % I don't even think you can pass arguments to f like this withing fminbnd
[Xopt, Fopt] = arrayfun(@(a, b, x1, x2) opt(a, b, x1, x2), A, B, X1, X2);
The first one is more readable.