Simplest would be to move all of the functions into a single m-file and turn the outer script into a function and thereby be able to get rid of the (ugh!!) globals and then usearrayfun to pass the required data.
Your next mission, should you choose to accept, is to recode a new solution using one of the supplied Matlab solvers.
Best Answer