Fminunc and dynare

Hi,
I solve my model using a second order approximation in Dynare. Now, I am trying to find those parameter values that maximize the value of one of the variables in my model. I am able to create a grid of parameter values and search for those values that maximize the variable of interest but if I try to be more rigorous and use the fminunc command in matlab I encounter the following problems:
-How to define the function to maximize since this value does not come from a single equation but from a second approximation that dynare does for me and it is stored in oo_.mean
-How to run the dynare code without assigning a specific value to the parameters I am searching for.
Please, any ideas will be highly appreciated
Thanks in advance!