title: fminsearch error: DOUBLE cannot convert the input expression into a double array
body: <p>I am encountering a problem during an optimization exercise. I am trying to use fminsearch() in matlab to solve it. The following error is generated when the code is run: </p>
  
  <blockquote>
    <p>The following error occurred converting from sym to double: Error
    using symengine (line 59) DOUBLE cannot convert the input expression
    into a double array. If the input expression contains a symbolic
    variable, use VPA.</p>
    
    <p>Error in fminsearch (line 190) fv(:,1) = funfcn(x,varargin{:});</p>
    
    <p>Error in Optimization (line 22) sol2 = fminsearch(J, x0);</p>
  </blockquote>
  
  <p>The script I use can be seen below. The f is the minimization problem where g1 &amp; g2 are constraints. The p is there so that I can turn it into  for loop later.</p>
  
  <pre><code>syms x1 x2 x3 x4;
  syms p;
  
  f = x1.^4 - x3.^2 + x1*x3 + x2*x4 - 5*x2 + 3;
  g1 = x1.^2 + x2.^2 + x3.^2 + x4.^2 - 1;
  g2 = x1 + x3 - 1;
  
  x0 = [2 2 2 2];
  p = 3;
  
  J = @(x1,x2,x3,x4) sym(f + p * g1.^2 + g2.^2);
  sol2 = fminsearch(J, x0);
  </code></pre>
  
  <p>This Stackoverflowpost has the same problem but in another perspective.According to this post it might be a problem with allocating the in a valid way. I tried a few different ways to solve my problem. I have tried matlabFunction() and putting the function in a seperate file.</p>
  
  <p><a href="https://stackoverflow.com/questions/21818223/if-the-input-expression-contains-a-symbolic-variable-use-the-vpa-function-inste">If the input expression contains a symbolic variable, use the VPA function instead?</a></p>
  
  <p>Thanks in advance for the help.</p>