## Passing optimValues to the objective function using fminunc

### Phil (view profile)

on 21 Aug 2013

I am having issues with passing the optimization information, namely the gradient and the iteration, to the objective function to be used therein.

Currently, I am simply calling optimValues in such a way:

```[x,fval,output,grad,hessian] = fminunc(@nestedfcn, x)
```
```function[fval, fgrad] = nestedfcn(x)
```
```      fval = fcnCalc(x);
iter = 0.01*optimValues.iteration;
```      g = -x + 0.1;
r = 10^iter;```
```      fval = fval + r*fgrad/g;
end```

Unfortunately, it does not get the desired result even when I pass optimValues into nestedfcn.

If anyone has an idea on how I might be able to use the optimValue information in my objective function, I would greatly appreciate it.

## Products

on 21 Aug 2013
Edited by Matt J

### Matt J (view profile)

on 21 Aug 2013

There is no reason your objective function or gradient calculation should depend on the iteration number or any other field of optimValues. The gradient and value calculations should be derived purely from x and from the mathematical form of the function you are minimizing.

The optimValues structure (which you obtained from OutputFcn?) is meant purely for managing the optimization algorithm, i.e., examining its progress and imposing any additional stopping criteria on the algorithm that you might wish.

Phil

### Phil (view profile)

on 21 Aug 2013

I believe that I am wrong in regards to the gradient after reassessing it, thanks for pointing that out, but the iteration count would be very helpful to update the barrier coefficient, but I might have to implement a counter.

Matt J

### Matt J (view profile)

on 21 Aug 2013

In that case though, r should be a fixed parameter of B(x) and you should not be changing it until B(x) has been fully minimized (or up to some appropriate stopping criterion). In other words, you should be calling fminunc in an outer loop, using it to solve the sub-problem of minimizing B(x,r) w.r.t. x. The parameter r would only evolve in the outer loop.

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi