Let me see. The use of globals here is unecessary, better would have been to use anonymous functions. Globals just complicate how variables get passed around, and make debugging code more difficult. But global variables did not cause the problem. It is just a programming style thing that people learn to dispose of when they learn to use functions properly.
Next, there is the problem that by creating a function with break points, as they move around the problem becomes non-differentiable. And fmincon does not perform well on non-differentiable problems. It can survive, but GA might be a better choice. Again, this is not a major problem, but possibly a minor one.
That all still leave the question begging an answer. Why did fmincon get upset and fail? The failure is a simple one. Fmincon was told there was an unknown vector, of length 2. And this is how fmincon works, as do all optimizers. If you have two unknowns, then you need to have a VECTOR of length 2 as the set of unknown parameters.
But the objective function was written as a function of TWO variables, p1 and p2, NOT a VECTOR of length 2, which would be one variable.
So what was the error message?
"Not enough input arguments."
fmincon understands the function will be passed ONE argument, here, a vector of length 2. How you want to use that vector is up to you.
When you have a problem like this, you need to write the objective function like this:
function f_v = ObjFun(P12)
p1 = P12(1);
p2 = P12(2);
And that is why fmincon failed, at least that was the immediate cause of failure. There may indeed be other problems in the code, but to completely debug it would require knowledge of what the code should be doing. It would force me to spend a great deal of time to get into the head of the OP, to understand what they wanted to do, to unravel how they were writing this code, and what they wanted to do, and how to fix it to compute what they wanted to see. Sorry, but that is a great deal of depth.