building matricies and fitting