Is there a specific reason you are not using the built-in functions "regress" or "polyfit" (if for some reason you need to know the coefficients of your polynomial function)?
To do what you demand you have to put all your calculations into one function, the parameter of which would be the two data vectors and possibly the order if you don't want to be of second order all the time. The output would be the vector a of coefficients.
But unless you have a very good reason not to do so I would suggest using regress or polyfit.