I want to understand the DFT matrix better (starting with the real part first).
- I'm first computing a DFT matrix by calculating the FFT of an identity matrix ( I can do
sp.linalg.dftand I get the same result anyway while the former is faster )
dft_matrix = np.fft.fft(np.eye(nelems))
- Second, I compute, say, the 20th row of the DFT from first principles using the cosine function
fi = 20
dotprod_row_test = np.cos(2 * np.pi * fi * np.linspace(0, 1, nelems))
If I compare the resulting values in the 20th row of these two, they don't match exactly?

BACKGROUND: I was trying to compute the FFT through different methods and I found that the higher frequencies didn't match exactly. Backtracking, I found that the DFT matrix I "compute from first principles" is not correct.
The below is a slightly modified version of your code which may be useful. In particular, the main change is with the line:
The original version was not correctly stepping from 0 to nelems-1 in the argument of the cosine. In particular, the factor should be $\frac{2 \pi}{nelems}$ with the index running from 0 to nelems-1, not 0 to nelems. Please see the code below for a running implementation.
I hope this helps.