# Gram matrices in the Rayleigh-Ritz algorithm

I want to get the math behind of the Rayleigh-Ritz Procedure (that minimize Rayleigh quotient) But when I look at the code (*), I cannot understand: Why are Gram matrices in the Rayleigh-Ritz procedure constructed this way? And why we should solve the eigenproblem with Gram matrices?

Can someone explain why we use Gram matrices or advice a paper that covers this? I googled but didn't find any description of the Gram matrix into Rayleigh-Ritz

If we have an eigenproblem $Ax = \lambda Bx$ and a subspace defined by basis vectors in a matrix $S$, then the projections of eigenvectors on $S$ are the solutions of $S^TASx_i = \lambda S^TBSx_i$. (definition of the Rayleigh-Ritz procedure)
If $S$ defined as a set of vectors $X_i$ = ($v_{i1} ... v_{in}$) that has some senses, we can write the matrix multiplication in the block form - the form gives a Gram matrix.