created matrix averaging function