From a quick glance over your code -
1> Add comments in your code. It's difficult to understand what you are trying to do without any relevant information.
2> Avoid using global. Pass the variables to the local functions as inputs.
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!