How to segment frequency bands after FFT and calculate power?

I have been working with EEG signal. I have raw EEG data for a 2-second (i.e. $t=2$) duration. My objectives are:

1. Transforming these raw data from time domain to frequency domain.
2. Segmentation into two frequency bands: $\left[4 - 8\textrm{ Hz}\right]$ and $\left[9 - 13\textrm{ Hz}\right]$.
3. Calculating the average power of these two bands separately.

I am doing the signal analysis in MATLAB. Sampling frequency is $512\textrm{ Hz}$. I have set the frequency resolution to $0.5\textrm{ Hz}$. For the first objective, I have used the fft function to transform the data.

freq = fft(x);  // x is my eeg data


I'm not sure on how to proceed in the second objective but I did in the following way. Since the frequency resolution is $0.5\textrm{ Hz}$, the bin numbers ($9$ to $17$) represent $\left[4 - 8\textrm{ Hz}\right]$. So, I did

band1 = freq(9:17);


Finally, to calculate the average power of a band, I used bandpower function.

power = bandpower(band1);


Your procedure is mostly correct. You should also add the bins corresponding to the negative frequencies -8Hz to -4Hz, which appear in the final bins of the fft result: the first bin corresponds to frequency 0Hz, the second to frequency $f_s/N$ = 0.5Hz, and so on. The last bin corresponds to frequency $f_s(N-1)/N$, which also corresponds to frequency $-f_s/N$.
I'd suggest using bandpower directly in the form p = bandpower(x,fs,freqrange). Here you provide the signal, the sampling frequency, and the frequency range, which is what you want.