MATLAB: How to dynamically change the number of nonlinear constraints using fmincon without errors

constraintfminconMATLABnonlinearoptimizationsqp

I'm running an optimization program using SQP and FMINCON that can dynamically change the number of nonlinear constraints during each iteration. However, whenever the number of nonlinear constraints changes I get the following error:
Error using sqpLineSearchMex
Provided nonlinear constraint does not have the correct number of elements: the value returned had X elements instead of the expected Y.
The number of constraints is based on the number of vertices of a polygon created by intersecting a plane with some spatial geometry, so different planar cross sections produce polygons with different numbers of vertices. The optimizer can control the position of the plane, and thus the number of vertices (and constraints) is constantly changing.
Is there a good way to handle this?

Best Answer

You will need to populate the nonlinear constraints so that it always returns the maximum number of entries that you might ever possibly use during a run. Set the unused ones to zero.